Why you shouldn’t use delegates in Swift

https://medium.cobeisfresh.com/why-you-shouldn-t-use-delegates-in-swift-7ef808a7f16b

這篇文章有示範如何使用 delgates 和 Block,在 Swift 中稱為 Protocols 和 Closures

delgates (Protocols)

protocol NetworkServiceDelegate {
    func didCompleteRequest(result: String)
}
class NetworkService {
    var delegate: NetworkServiceDelegate?

    func fetchDataFromUrl(url: String) {
        API.request(.GET, url) { result in
            delegate?.didCompleteRequest(result)
        }
    }
}

class MyViewController: UIViewController, NetworkServiceDelegate {

    let networkService = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()
        networkService.delegate = self
    }
    func didCompleteRequest(result: String) {
        print("I got \(result) from the server!")
    }
}

Block callback function (Closures)

class NetworkService {

    var onComplete: ((result: String)->())? //an optional function

    func fetchDataFromUrl(url: String) {
        API.request(.GET, url) { result in
            onComplete?(result: result) 
//                    ^ optional unwrapping for functions!
        }
    }
}

class MyViewController: UIViewController {

    let networkService = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()
        networkService.onComplete = { result in
            print("I got \(result) from the server!")
        }
    }
}

results matching ""

    No results matching ""