Delegates in swift?

前端 未结 12 1328
天命终不由人
天命终不由人 2020-11-22 03:27

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

12条回答
  •  [愿得一人]
    2020-11-22 04:08

    First class:

    protocol NetworkServiceDelegate: class {
    
        func didCompleteRequest(result: String)
    }
    
    
    class NetworkService: NSObject {
    
        weak var delegate: NetworkServiceDelegate?
    
        func fetchDataFromURL(url : String) {
            delegate?.didCompleteRequest(url)
        }
    }
    

    Second class:

    class ViewController: UIViewController, NetworkServiceDelegate {
    
        let network = NetworkService()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            network.delegate = self
            network.fetchDataFromURL("Success!")
        }
    
    
    
        func didCompleteRequest(result: String) {
            print(result)
        }
    
    
    }
    

提交回复
热议问题