所以第一个错误是因为您试图在可以执行的任何地方之外调用委托函数。您需要创建一个调用该函数的函数,或者在 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()