協議主要為一個特定的任務和功能定義一個方法、屬性和其他要求,你也可以理解協議就是一種要遵循的規范。
學過設計模式的,都知道工廠模式,如果你不知道可以查閱我的博文《[23設計模式之工廠方法(FactoryMethod)](http://blog.csdn.net/y550918116j/article/details/48596527)》,工廠模式就是一種協議的體現。在Java中,是用接口定義協議的;在OC中,主要用于代理。
除了已有的協議,你還可以像擴展類一樣擴展協議。這些擴展的協議可以實現也可以直接使用。
## 語法
協議語法使用了關鍵字protocol,和其他類型不同的是,它是規范的指定者,無須去實現。下面是一個空得協議。
~~~
protocol SomeProtocol {
// protocol definition goes here
}
~~~
協議可以被結構體繼承,
~~~
struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
}
~~~
協議也可以被類繼承,當然這是它最主要的功能。
~~~
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
~~~
### 協議
這里我們設計一個協議,并實現一個簡單方法。我們在這里使用了一個簡單方法。
~~~
protocol YJSomeProtocol {
func test()
}
~~~
編寫一個類去實現這個協議。
~~~
class YJSomeClass: YJSomeProtocol {
func test() {
print(__FUNCTION__)
}
}
let yjs = YJSomeClass()
yjs.test()
~~~
如果你想在類型中使用類型方法,可以在func前加static。
~~~
static func test()
~~~
你還可以讓該協議只能由class去實現,只需讓協議去繼承class
~~~
protocol YJSomeProtocol: class
~~~
## 代理
在Swift中有各種各樣的代理,這些代理都是通過協議來規范的,想知道更多關于代理模式的實現詳見我的博文《[23設計模式之代理模式(Proxy)](http://blog.csdn.net/y550918116j/article/details/48605595)》。
## 繼承
協議也支持繼承。
~~~
protocol YJAnotherProtocol: YJSomeProtocol {
// 協議可繼承
}
~~~
繼承的好處就是我們可以在一些公共的協議上,添加我們的協議,使之具有延伸性。
## 可選
在swift中又可選鏈,也就是‘?’和’!’。在這里我們考慮到這種情況,有一個協議里面有5個方法,其中兩個方法是必須的,其他3個方法,繼承的類不必強制去實現。
在OC中就有這種機制@optional,在swift也可以這樣使用,但是@optional是OC
的特性。因此,我們想使用這種特性的時候,就需要借助@objc。@objc可以理解為swift和oc的橋梁。
~~~
@objc protocol YJSomeProtocol:class {
// class代表只用類才能實現這個協議
func test()
// @objc:OC特性,代表可以使用optional特性。optional可選的方法
optional func testOptional()
}
~~~
但是這樣對實現類有一定的影響,因為這個特性是OC的。而OC中所有的類都是繼承NSObject,故實現這個協議的類也要繼承NSObject。
~~~
class YJSomeClass:NSObject, YJSomeProtocol {
func test() {
print(__FUNCTION__)
}
}
~~~
## 擴展
協議也支持擴展extension,這也相當于可選。只是在擴展的協議中,需要實現方法。
~~~
extension YJSomeProtocol {
func testExtension() {
print(__FUNCTION__)
}
}
~~~
實現類可以實現這個方法,也可以不實現這個方法。
## 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-11-2 | 根據 [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Protocols總結 |
版權所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結構體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運算符(Advanced Operators)