简体   繁体   中英

Swift 3 Delegate function not called

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM