Swift - Protocol&Delegate 露易兹才人小剧场

//看门狗经典场景解释代理委托机制

//

//  ViewController.swift

//  ProtocolDelegate

//

//  Created by sz on 16/1/1.

//  Copyright (c) 2016年 sz. All rights reserved.

//

import UIKit

//自定义一个协议

protocol HouseSecurityDelegate {

func handleIntruder()

}

//持有遵守协议者(代理人)的主人

class House: NSObject {

var delegate:HouseSecurityDelegate?

var name:String?

func burglarDetected()

{

print("im " + name!)

println(" i need a dog")

delegate?.handleIntruder()

}

}

//代理方--才狗! 汪汪 !(注意Swift遵守协议是继承语法,是冒号)

//看门狗类继承了NSObject,HouseSecurityDelegate

//Swift在你对协议的必选方法未实现时会报错(does not conform to)

class GuardDog: NSObject,HouseSecurityDelegate {

//遵守原则,谁继承,谁实现方法

func handleIntruder() {

println("614 im saito")

}

}

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

let myhouse = House()

myhouse.name = "louise"

myhouse.burglarDetected()

let saito = GuardDog()

myhouse.delegate = saito

myhouse.burglarDetected()

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

你可能感兴趣的:(Swift - Protocol&Delegate 露易兹才人小剧场)