- //1. 协议的定义
- protocol SportProtocol{
- //默认情况下,协议中的方法都是必须实现的方法
- func playBasketball()
- func playFootball()
- }
- //2. 定义类,并且遵守协议
- class teacher : SportProtocol{
- func playFootball() {
- print("踢足球")
- }
- func playBasketball() {
- print("打篮球")
- }
- }
- //3.LJStudent 继承自NSObject,然后遵守的是SportProtocol协议
- class LJStudent : NSObject,SportProtocol{
- func playFootball() {
- print("踢足球")
- }
- func playBasketball() {
- print("打篮球")
- }
- }
- // 4.协议在代理设计模型中的使用
- /*
- 定义协议时,协议后面最好跟上:class ,表明这个协议只给类用(否则结构体,枚举类型也可以使用这个协议)
- delegate的属性最好用weak,用于防止产生循环引用
- */
- protocol BuyTitcketDelegate: class{
- func buyTitcket()
- }
- class myPersonClass{
- //定义代理属性
- weak var delegate:BuyTitcketDelegate?
- func goToBeijing() {
- //如果这里的delegate存在的话,才会去执行buyTitcket这个函数,否则就不执行buyTitcket这个函数了
- delegate?.buyTitcket()
- }
- }
- //5. 如何让协议中的方法是可选方法
- // optional 属于OC 特性,如果协议中有可选的方法,那必须在proctocol前面加上@objc,也需要在optional前面加上@objc
- @objc protocol TestProtocol{
- @objc optional func test()
- }
- class Dog : TestProtocol{
- //这个方法可以执行,也可以不执行,就变成了可选类型了
- func test() {
- }
- }