引用Apple Swift團隊的一句話:
At the heart of Swift's design are two incredibly powerful ideas: protocol-oriented programming and first class value semantics. Each of these concepts benefit predictability, performance, and productivity, but together they can change the way we think about programming.
用值類型與面向協議的方式來編寫你的App,你會發現,對比Objective-C,Swift簡直强大得令人驚喜。
先看看OC中常見的、需要Copy的類型,比如NSString、NSArray、NSDictionary……通常我們會把NSString聲明為copy,為什麼?如果把一個NSString聲明為strong:
@property (strong, nonatomic) NSString *str;
然後這樣調用:
NSMutableString *mutableStr = [@"Leo" mutableCopy]; self.str = mutableStr; [mutableStr appendString:@" MobileDeveloper"]; NSLog(@"%@", self.str); // Leo MobileDeveloper
問題就出在這裡:NSString本是不可變對象,但我的str卻在不知不覺中被改掉了。為了更安全,很多類型都採用copy來操作。
在Swift中,Class是引用類型,Struct和Enum是值類型。引用類型在傳遞時具有隱式共享(implicit sharing)——默認是同一個內存對象的引用;而值類型在傳遞時都會copy。比如:
class Person {
var name: String
var age: UInt
init(name: String, age: UInt) {
self.name = name
self.age = age
}
}
當你傳遞它、又不小心在某處改了某個屬性,會發現原始對象也被改動了(即使把Person聲明為let):
let jack = Person(name: "Jack", age: 23) let temp = jack temp.age = 24 print(jack.age) // 24
這樣會導致:實例在多處都可能被修改,潛伏著你注意不到的代碼耦合;實例依賴外部狀態,使單元測試變得困難,甚至通過了單元測試仍可能有Bug。
再看值類型:
struct Person {
var name: String
var age: UInt
}
let jack = Person(name: "Jack", age: 23)
var temp = jack
temp.age = 24
print(jack.age) // 23
值類型的最大優勢是「不可變狀態」:拿到它,你就不必擔心別處會修改它。如果你懂一點函數式編程語言(比如Haskell),一定了解不可變狀態帶來的代碼可讀性、可維護性與可測試性上的種種好處。
網上搜索,一定有很多博客告訴你「值類型用在簡單的Model上」。但別人的觀點就一定正確嗎?當然不是。值類型不僅能用在Model上,從MVVM的角度看,它也能用在View、Controller和ViewModel上,並帶來諸多好處。WWDC 2016的視頻《Protocol and Value Oriented Programming in UIKit Apps》就介紹了值類型在View的Layout以及Controller的Undo中的應用。
引用Swift官方描述,以下場景可優先考慮值類型:
· 這個數據結構主要是為了封裝一系列相關的值;
· 傳遞時應該傳Copy而非引用;
· 數據結構本身存儲的類型也是值類型;
· 這個數據結構不需要繼承。
值類型通常要遵循Equatable,以保證能用 == 比較。比如:
struct Point: Equatable {
var x, y: CGFloat
}
func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
看到這裡,有經驗的你一定在想:值類型每次都Copy,不會有性能問題嗎?絕大部分時候沒有。而且相比Class,Struct往往性能更好,因為:
· 通常Struct在棧上分配內存,Class在堆上分配。堆上分配性能低於棧,因為堆上要透過加鎖等操作來保證多線程安全。
· Struct無需引用計數,Class則需要,引用計數會帶來隱式的額外開銷。
· Struct不能繼承,方法執行時是靜態派發(static dispatch);Class是動態派發(dynamic dispatch),需透過virtual table動態查找方法。
Tips:若想深入了解Swift的性能問題,推薦看看WWDC 2016的《Understanding Swift Performance》。
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.(協議定義了一個功能所需的方法、屬性及其他必要條件的藍圖)
也就是說,協議是「功能抽象」的體現,本身只提供一套規則。
Swift協議是一種類型,意味著你可以:把它作為函數的參數或返回值;宣告一個常量、變量或屬性;作為容器類型(Array/Dictionary)的元素。比如:
protocol Drawable {
func draw()
}
struct Circle: Drawable {
var center: CGPoint
var radius: CGFloat
func draw() {
print("Draw circle at \(center) with radius \(radius)")
}
}
struct Line: Drawable {
var from, to: CGPoint
func draw() {
print("Draw line from \(from) to \(to)")
}
}
struct Chart: Drawable {
var items: [Drawable]
func draw() {
items.forEach { $0.draw() }
}
}
let circle = Circle(center: CGPointMake(10, 10), radius: 5)
let line = Line(from: CGPointMake(10, 10), to: CGPointMake(15, 10))
let chart = Chart(items: [circle, line])
chart.draw()
因為協議本身是一種類型,你只需關注抽象本身——上例中我只關心 Drawable(可繪制),至於具體怎麼實現,並不重要。
protocol Drawable {
func draw()
}
protocol AnotherProtocol: Drawable {
func anotherFunc()
}
透過extension,可以為協議提供默認實現:
extension Drawable {
func printSelf() {
print("This is a drawable protocol instance")
}
}
// 然後就可以這樣調用
let circle = Circle(center: CGPointMake(10, 10), radius: 5)
circle.printSelf()
可透過Extension的方式,讓一個現有類型實現某個協議。比如下面是最簡單的Swift Model:
struct Person {
var name: String
var age: Int
var city: String
var district: String
}
struct Room {
var city: String
var district: String
}
突然有一天,我們有個需求:要打印Person和Room的地址信息,怎麼辦?
方式一:直接修改Person和Room的實現——這樣就違背了「對擴展開放、對修改封閉」的原則。
方式二:透過Swift協議擴展:
// 定義新需求的協議
protocol AddressPrintAble {
var addressDescription: String { get }
}
// 透過擴展,讓 Person 和 Room 實現協議
extension Person: AddressPrintAble {
var addressDescription: String { return "\(city) \(district)" }
}
extension Room: AddressPrintAble {
var addressDescription: String { return "\(city) \(district)" }
}
這樣,你就能把Person、Room的實例當作AddressPrintAble類型來使用。因為協議是一種類型,你甚至能把它們存進同一個數組:
let leo: AddressPrintAble = Person(name: "Leo", age: 24, city: "Shanghai", district: "XuHui")
let room: AddressPrintAble = Room(city: "Shanghai", district: "Xuhui")
var array = [AddressPrintAble]()
array.append(leo)
array.append(room)
array.forEach { (address) in
print(address.addressDescription)
}
透過協議來擴展Cocoa類,是一個很常見也很實用的技巧。
擴展協議時,可用where語句進行約束,只對滿足特定條件的類型生效。比如初始化一個NSObject子類時,我們希望能有初始化配置,如果NSObject能提供一個操作符讓我們做配置就好了,於是:
public protocol SetUp {}
extension SetUp where Self: AnyObject {
public func SetUp(@noescape closure: Self -> Void) -> Self {
closure(self)
return self
}
}
extension NSObject: SetUp {}
然後就能這樣調用:
let textfield = UITextField().SetUp {
$0.frame = CGRectMake(0, 0, 200, 30)
$0.textAlignment = .Center
$0.font = UIFont.systemFontOfSize(14)
$0.center = view.center
$0.placeholder = "Input some text"
$0.borderStyle = UITextBorderStyle.RoundedRect
}
僅能用在Class上的協議:
protocol MyProtocol: class
協議組合(Protocol Composition)——同時遵循兩個協議:
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }
func wishHappyBirthday(celebrator: protocol<Named, Aged>) {
print("Happy birthday \(celebrator.name) - you're \(celebrator.age)!")
}
Self——協議方法中的Self表示實際遵循協議的類型:
protocol Orderable {
func compare(other: Self) -> Bool
}
extension CGPoint: Orderable {
func compare(other: CGPoint) -> Bool {
// 注意,這裡的 other 已是 CGPoint 類型了
return self.x > other.x && self.y > other.y
}
}
associatedtype——當協議中有不確定類型的對象時,可用associatedtype聲明:
protocol Listable {
associatedtype Content
var dataList: [Content] { get }
}
extension CGPoint: Listable {
typealias Content = CGFloat
var dataList: [Content] {
get { return [x, y] }
}
}
協議會讓你的代碼變得前所未有的靈活。以我編寫PullToRefreshKit為例,就用協議增強了可擴展性:對於下拉刷新Header,我定義了Protocol RefreshableHeader來抽象任意可刷新的View:
public protocol RefreshableHeader: class {
func distanceToRefresh() -> CGFloat
func percentUpdateWhenNotRefreshing(percent: CGFloat)
func releaseWithRefreshingState()
func didBeginEndRefershingAnimation(result: RefreshResult)
func didCompleteEndRefershingAnimation(result: RefreshResult)
}
再借助協議與泛型,任何遵循該協議的UIView子類,都能作為我的Refresh Header:
public func setUpHeaderRefresh<T: UIView, T: RefreshableHeader where T: UIView>(header: T, action: () -> ()) -> T {
// ...
}