我怎样才能写一个关于如何在 Swift 5 中使用委托的简单示例

How can I write a simple example on how to use delegates in Swift 5

我想写一个简单的例子来说明委托在 Swift 中是如何工作的。我已经设置了一个 class、一个协议和另一个遵守该协议的 class。但是我在两个不同的地方遇到了同样的错误。我在 xcode 中创建了一个简单的 swift 命令行工具,我的所有代码都在 main.swift 中。除了了解委托的工作原理外,该代码没有任何实际功能。

错误信息如下:

Consecutive declarations on a line must be separated by ';'
Insert ';'
Expected '(' in argument list of function declaration
Expected '{' in body of function declaration
Expected 'func' keyword in instance method declaration
Insert 'func '
Expected declaration
Invalid redeclaration of 'delegate()' //or anything() in the other error

代码如下:

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 中调用它。制作示例时,请尝试使用真实世界的概念来为您的示例建模。您可以做一些类似 Conductor class 和 Train Class 的事情。售票员可以实施一些控制列车速度的控制协议。

无论如何,你的第二个错误是因为self还没有被初始化。要将变量分配给 self,您必须先初始化 class,这样您就可以

init() {
   anything?.delegate = self
}

欢迎私信以进一步了解这个概念,稍后我会post在这里举一个完整的例子。

编辑:完整示例,欢迎提问

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()

在游乐场文件中编辑您的代码:

protocol MyProtocol {
    func doAnything()
}

class MainClass {

    var delegate: MyProtocol? = nil

    func callMeForGetCallBackWithDelegate() {
        // send call back inside any function after call or inside in init
        if let delegate = self.delegate {
            delegate.doAnything()
        }
    }
}


class OtherClass: MyProtocol {

    let anything = MainClass()

    init() {
        self.anything.delegate = self // set delegate in init or set inside any function
        self.anything.callMeForGetCallBackWithDelegate()
    }

    func doAnything() {
        print("text")
    }
}

let otherClass = OtherClass()