八舷手、泛型下標(biāo)
下標(biāo)現(xiàn)在可以有泛型參數(shù)和返回類型.
最權(quán)威的例子莫過于表示 JSON 數(shù)據(jù): 你可以定義一個(gè)泛型下標(biāo)來保持調(diào)用者期望類型的內(nèi)容.
struct JSON {
fileprivate var storage: [String:Any]
init(dictionary: [String:Any]) {
self.storage = dictionary
}
subscript<T>(key: String) -> T? {
return storage[key] as? T
}
}
let json = JSON(dictionary: [
"城市名": "北京",
"國(guó)家代碼": "cn",
"人口": 21_710_000
])
// 沒必要用 as? Int
let population: Int? = json["人口"]
另一個(gè)例子: Collection 的一個(gè)下標(biāo)接受一個(gè)泛型索引序列, 并返回一個(gè)這些索引所在的數(shù)組:
extension Collection {
subscript<Indices: Sequence>(indices: Indices) -> [Element] where Indices.Element == Index {
var result: [Element] = []
for index in indices {
result.append(self[index])
}
return result
}
}
let words = "我 思 故 我 在".split(separator: " ")
words[[1,2]]
九厦凤、NSNumber 橋接
修正部分危險(xiǎn)行為當(dāng)橋接Swift原生數(shù)字類型和NSNumber的時(shí)候.
import Foundation
let n = NSNumber(value: UInt32(301))
let v = n as? Int8 // nil(Swift 4). Swift 3會(huì)是45 (試試看!).
十萧恕、類和協(xié)議的組合
你現(xiàn)在能寫出OC這段 UIViewController <SomeProtocol> * 在Swift中的等價(jià)代碼, 比如聲明這樣一個(gè)變量,這個(gè)變量擁有實(shí)體類型并同時(shí)遵守若干協(xié)議. 語(yǔ)法 let 變量: 某個(gè)類 & 協(xié)議1 & 協(xié)議2.
import Cocoa
protocol HeaderView {}
class ViewController: NSViewController {
let header: NSView & HeaderView
init(header: NSView & HeaderView) {
self.header = header
super.init(nibName: nil, bundle: nil)
}
required init(coder decoder: NSCoder) {
fatalError("not implemented")
}
}
// 不能傳一個(gè)簡(jiǎn)單的NSView進(jìn)去因?yàn)椴蛔袷貐f(xié)議
//ViewController(header: NSView())
// 錯(cuò)誤: argument type 'NSView' does not conform to expected type 'NSView & HeaderView'
// 必須穿一個(gè) NSView (子類) 同時(shí)遵守協(xié)議
extension NSImageView: HeaderView {}
ViewController(header: NSImageView()) // 有用