我想写一个简单的示例,说明委托在Swift中的工作方式。我已经建立了一个类,一个协议和另一个遵守该协议的类。但是我在两个不同的地方遇到相同的错误。我在xcode中创建了一个简单的swift命令行工具,所有代码都位于main.swift中。除了学习委托的工作方式之外,该代码没有实际功能。
这是错误消息:
行上的连续声明必须以';'分隔
插入 ';'
函数声明的参数列表中应为'('。函数声明的
主体中应为'{'。
实例方法声明中的期望为'func'关键字。
插入'func'
期望的声明
'delegate()' //或中的任何内容的无效重新声明。其他错误
这是代码:
class MainClass {
var delegate: MyProtocol? = nil
delegate.doAnything() //getting 1st error here
}
protocol MyProtocol {
func doAnything()
}
class OtherClass: MyProtocol {
let anything = MainClass()
anything?.delegate = self //getting 2nd error here
func doAnything() {
print("text")
}
}
因此,第一个错误是因为您试图在可以执行的任何位置之外调用委托函数。您需要创建一个调用该函数或在init中调用它的函数。制作示例时,请尝试使用现实世界中的概念为示例建模。您可以做一些类似指挥班和训练班的事情。售票员可以实施一些控制协议来控制火车的速度。
无论如何,您的第二个错误是因为self
尚未初始化。要将变量分配给self
,您必须先初始化该类,这样您就可以
init() {
anything?.delegate = self
}
DM欢迎您进一步了解此概念,我将在此处稍作完整的示例。
编辑:完整的例子,随时问问题
import Foundation
enum Direction {
case north
case east
case south
case west
}
protocol VehicleControls {
var speed: Float {get set}
var direction: Direction {get set}
var numPassengers: Int {get}
func change(newSpeed: Float)
func change(newDirection: Direction)
func createNoise()
}
class Conductor {
var vehicle: VehicleControls
init() {
vehicle = Train(s: 1.5, d: .west, nP: 50)
}
func controlVehicle() {
vehicle.change(newSpeed: 2.5)
vehicle.change(newDirection: .east)
vehicle.createNoise()
print("\n")
}
}
class Train: VehicleControls {
var speed: Float
var direction: Direction
var numPassengers: Int
init() {
self.speed = 0
self.direction = .north
self.numPassengers = 0
}
init(s: Float, d: Direction, nP: Int) {
self.speed = s
self.direction = d
self.numPassengers = nP
}
func change(newSpeed: Float) {
print("changing speed from \(speed), to \(newSpeed)")
self.speed = newSpeed
}
func change(newDirection: Direction) {
print("changing direction from \(direction) to \(newDirection)")
self.direction = newDirection
}
func createNoise() {
print("Chugga, Chugga... Chugga, Chugga... CHOO CHOO")
}
}
class Car: VehicleControls {
var speed: Float
var direction: Direction
var numPassengers: Int
init() {
self.speed = 0
self.direction = .north
self.numPassengers = 0
}
init(s: Float, d: Direction, nP: Int) {
self.speed = s
self.direction = d
self.numPassengers = nP
}
func change(newSpeed: Float) {
print("changing speed from \(speed), to \(newSpeed)")
self.speed = newSpeed
}
func change(newDirection: Direction) {
print("changing direction from \(direction) to \(newDirection)")
self.direction = newDirection
}
func createNoise() {
print("HONK HONK, BEEP BEEP")
}
}
let newConductor = Conductor()
newConductor.controlVehicle()
newConductor.vehicle = Car(s: 60.56, d: .north, nP: 2)
newConductor.controlVehicle()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句