天天看點

Swift 5.2 新特性

  • 優雅處理轉義字元
let param = #"somestring"# // somestring中轉義字元不轉義,原樣輸出
print(param)
           
  • 允許在子產品中定義和标準庫中名稱一樣的類型

    比如在

    MyModule

    子產品中定義

    Result

public enum Result<T> {
    case value(T)
    case error(Error)
}
           

如果你在任何代碼中引入了

MyModule

,比如

import MyModule
func doSomething() -> Result<Int> {  }
           

這時如果你需要引用标準庫中的

Result

類型,你需要這樣做,否則

Result

将解析到

MyModule

中的

Result

  • @dynamiccalable屬性

    使用

    @dynamiccalable

    屬性後,調用函數就像使用簡單語句一樣。
@dynamicCallable struct ToyCallable {
    func dynamicallyCall(withArguments: [Int]) {}
    func dynamicallyCall(withKeywordArguments: KeyValuePairs<String, Int>) {  }
}

var x = ToyCallable()
x(1, 2, 3)
 // Desugars to `x.dynamicallyCall(withArguments: [1, 2, 3])`
        
x(label: 1, 2)
// Desugars to `x.dynamicallyCall(withKeywordArguments: ["label": 1, "": 2])`
           
  • 在枚舉中不支援可變參數

    例如:

enum X {
    case foo(bar: Int...) 
}
func baz() -> X {
    return .foo(bar: 0, 1, 2, 3) 
} 
           

在Swift5.2 中可變參數應該使用數組來代替

enum X {
    case foo(bar: [Int]) 
} 
func baz() -> X {
    return .foo(bar: [0, 1, 2, 3]) 
} 
           
  • Key paths

    支援ID密鑰路徑(\.self),一個可寫入的密鑰路徑,可以引用其整個輸入值
let id = \Int.self
var x = 2
print(x[keyPath: id]) // Prints "2"
x[keyPath: id] = 3
print(x[keyPath: id]) // Prints "3"
           
  • 條件編譯,相容Swift 5之前的代碼
#if compiler(<5)
extension MyType: _ExpressibleByStringInterpolation { /*...*/ }
#else
extension MyType: ExpressibleByStringInterpolation { /*...*/ }
#endif 
           
未完待續