gpt4 book ai didi

ios - 未调用 Swift 3 委托(delegate)函数

转载 作者:行者123 更新时间:2023-11-28 21:04:39 25 4
gpt4 key购买 nike

我正试图了解 Swift 委托(delegate)并偷/弄了一个 Playground,但似乎无法调用委托(delegate)函数。

protocol fBookDelegate:class {
func processData(data: String)
}

class fBook {

weak var delegate: fBookDelegate?

init() {
print("initialising fBook")
delegate?.processData(data: "hello world")
print("we should have printed")
}
}

class fMain: fBookDelegate {
init() {
print("initialising fMain")
let getfBook = fBook()
getfBook.delegate = self
print("all done let's rumble")
}

func processData(data: String) {
print("processing data from fBook with \(data)")
}
}

var controller = fMain()

有人能发现我的错误吗?

我得到的输出是

initialising fMain
initialising fBook
we should have printed
all done let's rumble

最佳答案

你可以这样使用:

import UIKit
protocol fBookDelegate:class {
func processData(data: String)
}
class fBook {
init(delegate: fBookDelegate?) {
print("initialising fBook")
delegate?.processData(data: "hello world")
print("we should have printed")
}
}
class fMain: fBookDelegate {
init() {
print("initialising fMain")
let getfBook = fBook(delegate: self)
print("all done let's rumble")
}
func processData(data: String) {
print("processing data from fBook with \(data)")
}
}

var controller = fMain()

输出:

initialising fMain
initialising fBook
processing data from fBook with hello world
we should have printed
all done let's rumble

关于ios - 未调用 Swift 3 委托(delegate)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46453743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com