SE-0249:將Key Path表達(dá)式作為函數(shù):(Root)->Value
// ? ?已知結(jié)構(gòu)體
struct User {
? ? let email: String
? ? let isAdmin: Bool
}
?生成一個(gè)郵箱地址的數(shù)組,過(guò)濾管理員剪撬,管理員數(shù)組
users.map { $0.email }?
users.filter { $0.isAdmin }
users.compactMap { $0.isAdmin }
采用新的表達(dá)式:\Root.value
users.map(\.email)
users.filter(\.isAdmian)
語(yǔ)法解釋?zhuān)篭Root.value相當(dāng)于{$0[keyPath: \Root.value]}
users.map(\.email) === user.map { $0[keyPath: \User.email] }
語(yǔ)法注意:\Root.value是方法(Root)->Value的縮寫(xiě)摄乒,當(dāng)使用臨時(shí)變量時(shí):
let kp = \User.email ? ? ? ?//????錯(cuò)誤?
let kp: (User) -> String = \User.email????// ? ?正確
let kp = \User.email as (User) -> String????// ? ?正確
users.map(kp)
編譯器做了什么?
let kp: (User) -> String = \User.email ?// ?代碼
let kp: (User) -> String = { kp in { root in root[keyPath: kp] } }(\User.email) ?// ?編譯器后的代碼
swift為啥添加該語(yǔ)法残黑?
This is a purely additive change and has no impact.//??
SE-0253:靜態(tài)方法自定義
callAsFunction:
struct Adder {
? ? var base: Int
? ? func?callAsFunction(_ x: Int) -> Int {
? ? ? ? return base + x
????}
? ? func callAsFunction<T>(_ x: T, bang: Bool) throws -> T where T: BinaryInteger {
? ? ? ? if bang { return T(Int(exactly: x)! + base) }
? ? ? ? else { retuurn T(Int(truncatingIfNeeded: x) + base) }
????}
}
let add = Adder(base: 3)
add(10) ? ?// => 13
try add(4, bang: true) // => 5
subscript:
struct Polynomial {
? ? let coefficients: [Float]
}
extension Polynomial {
? ? subscript(input: Float) -> Float {
? ? ? ? var result: Float = 0
? ? ? ? for (i, c) in coefficients.enumerated() {
? ? ? ? ? ? result += c * pow(input, Float(i))
????????}
? ? ? ? return result
????}
}
let polynomial = Polynomial(coefficients: [2, 3, 4])
print(polynomial.evaluated(at: 2)) // => 24
與閉包結(jié)合:類(lèi)似于代理
struct BoundClosure<T, F: (T) -> ()>: () -> () {
????var function: F
????var value: T
????func callAsFunction() { return function(value) }
}
let f = BoundClosure({ print($0) }, x) // instantiates BoundClosure<(underlying type of closure), Int>
f() // invokes call on BoundClosure
提高編譯結(jié)果準(zhǔn)確性:錯(cuò)誤代碼提示更準(zhǔn)確
優(yōu)化代碼不全:代碼提示更人性化
優(yōu)化編譯算法
· Whole Module (typically used for Release builds)
·?Incremental (typically used for Debug builds)