Reputation: 300
I'm trying to get my head around Swift delegates and stole/knocked-up a Playground but cannot seem to get the delegate function to be called.
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()
Can anybody spot my mistake ?
All I get for output is
initialising fMain
initialising fBook
we should have printed
all done let's rumble
Upvotes: 0
Views: 434
Reputation: 7485
You can use like this :
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()
output :
initialising fMain
initialising fBook
processing data from fBook with hello world
we should have printed
all done let's rumble
Upvotes: 2
Reputation: 31016
Here's one option for using your delegate:
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()
Another would be a custom init method that takes the delegate as a parameter.
Upvotes: 0