我正试图绕过Swift代表并偷走/敲打一个Playground,但似乎无法调用委托函数。
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
答案 0 :(得分:2)
您可以这样使用:
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
答案 1 :(得分:0)
以下是使用您的代理人的一个选项:
protocol fBookDelegate:class {
func processData(data: String)
}
class fBook {
weak var delegate: fBookDelegate?
init() {
print("initialising fBook")
}
func talkToMe() {
delegate?.processData(data: "hello world")
}
}
class fMain: fBookDelegate {
init() {
print("initialising fMain")
let getfBook = fBook()
getfBook.delegate = self
getfBook.talkToMe()
print("all done let's rumble")
}
func processData(data: String) {
print("processing data from fBook with \(data)")
}
}
var controller = fMain()
另一种方法是将委托作为参数的自定义init方法。