前言
本文是筆者學(xué)習(xí)Swift協(xié)議的筆記黄琼。
開始
OC中判斷是否遵守某個(gè)協(xié)議有對(duì)應(yīng)的方法狸剃,Swift中也有倦微,但是開始使用的時(shí)候遇到了問題:
self.conforms(to: LJCacheKitTableProtocol)
error: Cannot convert value of type 'LJCacheKitTableProtocol.Protocol' to expected argument type 'Protocol'
后來發(fā)現(xiàn)使用conforms方法來判斷是否遵守某個(gè)協(xié)議時(shí)梧兼,此時(shí)協(xié)議必須標(biāo)記為@objc女仰;
但是Swift中提供了其他的方式來判斷是否遵守某個(gè)協(xié)議:
is : 返回true或false
as? : 返回一個(gè)optional類型的遵守該協(xié)議的對(duì)象蹂窖,如果為nil則不遵守該協(xié)議
as! : 返回一個(gè)遵守該協(xié)議的對(duì)象轧抗,如果不遵守則出錯(cuò)
默認(rèn)的 Swift中協(xié)議中方法是必須實(shí)現(xiàn)的,如果想使用OC中optional類型協(xié)議方法瞬测,也必須標(biāo)記協(xié)議為@objc横媚。
針對(duì)這種情況纠炮,如果我們?cè)谠O(shè)計(jì)的協(xié)議中想要增加一些optional類型的方法,其實(shí)可以不用標(biāo)記協(xié)議為@objc灯蝴,換種思路恢口,可以重新設(shè)計(jì)協(xié)議,講其拆分為多個(gè)穷躁,根據(jù)需要去選擇遵守那個(gè)耕肩,同時(shí)Swift中支持Protocol Composition來組合多個(gè)協(xié)議。
以下是筆者的筆記:
property in protocol {get set};
method in protocol (mutating in enum and struct & init method in protocol);
protocol can use as type like String type;
use protocol implement delegate pattern;
use extension to conform protocol;
protocol can be inherited like class;
use AnyObject to create class-only protocol;
New: use & combine protocol and class type to make a new type( conform several different protocols and inherited from class);
use as(? !) or is to check object is conform some protocol, is just to get true or false , as can downcast;
mark protocol and methods in protocol as @objc can make these methods optional ;
protocol can add extension to provide default implemention , use where to add constraints to protocol extension;
最后
未完待續(xù)