Swift5.0更新内容

开发语言:Swift 5.0
开发环境:Xcode 10.2

参考资料:

更新文档

GithubDemo

苹果于19年3月发布了Swift5,在xcode10.2版本中可以使用Swift5,以下是Swift5的相关更新内容。

1、语言更新

更稳定的ABI和二进制兼容性

  • 什么是ABI:Swift通过ABI调用操作系统底层,在以前的Swift中,每个我们编写的app都会包含一个Swift库,而在Swift5中,这些库被内置在操作系统中,而app通过ABI调用系统的Swift,这样会使app的体积更小,运行速度更快,而且系统中会存在多个版本的Swift库,例如swift4,swift4.2,swift5,app可以通过ABI来调用特定的版本。

2、标准库更新

  • 使用UTF-8编码重新实现String,提高了运行效率
  • 改进了对字符串文本中原始文本的支持(使用#符号)
  • 增加了Result类型与SIMD类型
  • 增强了字符串插值,提高了序列化的灵活性
  • 改进了Dictionary和Set的性能

下面的例子展示了Swift5.0标准库的更新(GithubDemo)

2.1 Raw strings(原始字符串)

Swift5.0增加了创建原始字符串的功能,其中反斜杠和引号不再需要转义。这使得许多用例更加简单,尤其是正则表达式将更容易使用。

使用 #"...."# 来创建原始字符串

let old = "raw \"string\""   
let new = #"raw "string""#   

输出:raw "string

两者的结果是一样的,但是在raw strings中,我们不需要使用\来作为转义符号了

如果原始字符串中包含了"#,则需要使用##"..."##来创建

let new = ##"raw"#string"## 

输出:raw"#string

多行原始字符串使用#"""..."""#来创建

let new = #"""
raw                     
string
"""#

输出:
raw
string

使用#(value)在原始字符串中使用插值

 let temp = 63.4
 let new = #"raw string \#(temp)"#

输出:"raw string 63.4"

2.2 A standard Result type(标准Result类型)

顾名思义Result用于描述某个行为的结果,其定义如下:

enum Result where Failure : Error 

其中Success和Failure都是以泛型实现的,但Failure必须继承Error。

下面的例子展示了一个返回类型为Result的下载函数,返回类型包含了下载成功时的下载文件名或下载失败时的错误内容。

enum DownloadError:Error {
    case TimeOut
    case AddressNotFound
    case DownloadFailed
    case FileCountZero
}


func download(url:String?)->Result {
    guard url != nil else {
        return .failure(.AddressNotFound)
    }
    
    var connect = true
    guard connect else {
        return .failure(.TimeOut)
    }
    
    var download = true
    guard download else {
        return .failure(.DownloadFailed)
    }
    
    var downloadFileName = ""
    return  .success(downloadFileName)
}

判断result成功或者失败。

let result = download(url: "some url")
switch result {
case .failure(let error):
    print(error)
case .success(let name):
    print(name)
}

同时result还提供一个get函数,如果result成功则返回成功的值,反之抛出异常。

let result = download(url: "some url")
do {
    let success = try result.get()
} catch {
    switch error {
    case DownloadError.TimeOut:
        print("TimeOut")
    case DownloadError.AddressNotFound:
        print("AddressNotFound")
    case DownloadError.DownloadFailed:
        print("DownloadFailed")
    default:
        print("OtherError")
    }
}

同时result提供map与mapError函数来生成一个新的result类型

enum NewDownloadError:Error {
    case NewError
}

let result = download(url: "some url")
//Result
let newResult = result.map { (str) -> Int in
    return str.count
}

//Result
let newError = result.mapError { (error) -> NewDownloadError in
    return NewDownloadError.NewError
}
return true

假设我们有一个检查下载文件数量的函数

func CheckFileCount(path:String)->Result {
    let fileCount = 0
    guard fileCount != 0 else {
        return .failure(DownloadError.FileCountZero)
    }    
    return .success(fileCount)
}

我们在下载完毕后,想进行下载数量的检查

let fileCountResult = result.map { CheckFileCount(path: $0)}

这时得到了一个很奇怪的类型Result,DownloadError>,而事实上,我们期望得到一个Result类型的Result,此时可使用Result的flatMap函数来处理这个问题,就像Swift高阶函数中Array.flatMap一样,同样的,Result同时也提供了flatMapError来生成一个新的Result类型。

2.3 Customizing string interpolation(自定义字符串插值)

通常情况下,我们在字符串中使用(param)的方式来打印类型的相关信息,例如我们有如下的类型User:

struct User {
    var name: String
    var age: Int
}

同时我们想输出这个类型的相关信息,需要扩展String.StringInterpolation:

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: User) {
        let str = "name:" + value.name + "   age:" + String(value.age)
        
        appendLiteral(str)
    }
}

let user = User(name: "Guybrush", age: 33)
print("\(user)") //name:Guybrush   age:33

Swift的String类型中,有如下的构造函数,来通过DefaultStringInterpolation构造一个String。

@inlinable public init(stringInterpolation: DefaultStringInterpolation)

而DefaultStringInterpolation,提供了如下5个方法来输出插值,其中appendLiteral是通过一个String构造插值,而其他的appendInterpolation则提供了泛型的功能,通过任意类型T来构造差值

public struct DefaultStringInterpolation : StringInterpolationProtocol {

    @inlinable public mutating func appendLiteral(_ literal: String)
    @inlinable public mutating func appendInterpolation(_ value: T) where T : CustomStringConvertible, T : TextOutputStreamable
    @inlinable public mutating func appendInterpolation(_ value: T) where T : TextOutputStreamable
    @inlinable public mutating func appendInterpolation(_ value: T) where T : CustomStringConvertible
    @inlinable public mutating func appendInterpolation(_ value: T)
}

我们改写一下 appendInterpolation(_ value: User)

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: User) {
       
        let num = 10
        //调用默认的appendInterpolation(_ value:Int)
        appendInterpolation(num)
    }
}

let user = User(name: "Guybrush", age: 33)
print("\(user)") //10

使用ExpressibleByStringLiteral和expressiblebystring插值协议的组合,我们可以使用字符串插值创建整个类型,如果我们添加CustomStringConvertible,我们甚至可以将这些类型打印为我们想要的字符串。

要实现这一目标,我们需要满足一些具体的标准:

  • 我们创建的任何类型都应该符合ExpressibleByStringLiteral、expressiblebystring插值和CustomStringConvertible。只有当您想自定义打印类型的方式时,才需要使用后者。
  • 在你的类型 内部 需要是一个名为StringInterpolation并遵循StringInterpolationProtocol的嵌套结构体。
  • 嵌套结构体需要有一个初始化器,该初始化器接受两个整数,粗略地告诉我们它可以期望多少数据。
  • 它还需要实现一个appendLiteral()方法,以及一个或多个appendInterpolation()方法。
  • 你的主类型需要有两个初始化器,允许从字符串文字和字符串插值创建它。

以下是官方提供的例子(老实说,这段我看的不是很明白,不知道这个插值在实际应用中应该怎么样使用)

struct HTMLComponent: ExpressibleByStringLiteral, ExpressibleByStringInterpolation, CustomStringConvertible {
    struct StringInterpolation: StringInterpolationProtocol {
        // start with an empty string
        var output = ""

        // allocate enough space to hold twice the amount of literal text
        init(literalCapacity: Int, interpolationCount: Int) {
            output.reserveCapacity(literalCapacity * 2)
        }

        // a hard-coded piece of text – just add it
        mutating func appendLiteral(_ literal: String) {
            print("Appending \(literal)")
            output.append(literal)
        }

        // a Twitter username – add it as a link
        mutating func appendInterpolation(twitter: String) {
            print("Appending \(twitter)")
            output.append("@\(twitter)")
        }

        // an email address – add it using mailto
        mutating func appendInterpolation(email: String) {
            print("Appending \(email)")
            output.append("\(email)")
        }
    }

    // the finished text for this whole component
    let description: String

    // create an instance from a literal string
    init(stringLiteral value: String) {
        description = value
    }

    // create an instance from an interpolated string
    init(stringInterpolation: StringInterpolation) {
        description = stringInterpolation.output
    }
}


let text: HTMLComponent = "You should follow me on Twitter \(twitter: 6), or you can email me at \(email: "[email protected]")."

print(text) // You should follow me on Twitter @twostraws, or you can email me at [email protected].You should follow me on Twitter @twostraws, or you can email me at [email protected].

2.4 Dynamically callable types(动态调用类型)

动态调用类型是使变量可以像函数一样调用的语法糖,官方文档说它不太可能广泛流行= =!,但对于希望与Python,JS类似的语言交互的使用者来说,它非常重要。通过 @dynamicCallable 属性来实现这个语法糖,我们来看个例子

@dynamicCallable
class Math {
    func dynamicallyCall(withArguments:[Double]) -> Double {
        return withArguments.reduce(into: Double(0)) { (arg1, arg2) in
            arg1 += arg2
        }
    }
    
    func dynamicallyCall(withKeywordArguments:KeyValuePairs)->Double? {
        return withKeywordArguments.reduce(into: Double(1)) { (arg1, arg2) in
            arg1 *= arg2.value
        }
    }
}

我们使用@dynamicCallable属性定义了一个Math类,同时按照该属性的要求实现了2个函数,为了区分使用效果,withArguments:是将参数叠加,而withKeywordArguments:是将参数叠乘。接下来我们要定义2个Math的对象,然后像函数一样调用它们。

let add = Math()
let addResult = add(1,2,1) //addResult = 4
let multiply = Math()
let multiplyResult = multiply(param1:1, param2:2, param3:1) //multiplyResult = 2

显然,我们在调用add对象时,没有使用参数名,所以它最终调用的是withArguments:,计算了1+2+1的值,而我们在调用multiplyResult对象时,使用了param1,param2,param3,三个自定义的参数名,它最终调用的是withKeywordArguments:,计算了1*2*1的值。

使用@dynamicCallable有以下几点需要注意:

  • 可以在 structs, enums, classes, protocols上使用,但不能在extension上使用。
  • 增加@dynamicCallable不影响其原有的任何使用方式。
  • 至少要实现withKeywordArguments:和withArguments:两者其中一,并且两者都支持异常抛出。
  • 如果只实现了withKeywordArguments:,依然可以使用没有参数名的方式,此时获取的参数名全部为空。
  • withArguments:的参数必须遵循ExpressibleByArrayLiteral协议,而返回值没有类型约束。
  • withKeywordArguments:的参数必须遵循ExpressibleByDictionaryLiteral协议并且Key必须遵循ExpressibleByStringLiteral协议,而返回值没有类型约束。

2.5 Handling future enum cases (处理未来的枚举分支)

假设我们定义了一个enum,它默认有4个case:

enum ErrorTest {
    case Error1 
    case Error2
    case Error3
    case Error4
}

同时有个函数处理这个enum,我们只处理error1和error2,剩下的error3和error4我们使用default来处理。

func PrintError(err:ErrorTest) {
    switch err {
    case .Error1:
        print("error1")
    case .Error2:
        print("error2")
    default:
        print("other")
    }
}

随着时间的推移,我们需要增加一个新的case,error5并且我们想要单独处理它,类似:

func PrintError(err:ErrorTest) {
    switch err {
    case .Error1:
        print("error1")
    case .Error2:
        print("error2")
    case .Error5:
        print("error5")
    default:
        print("other")
    }
}

但程序中用到ErrorTest的地方太多,Swift不会警告我们增加了新的error5,所以提出了@unknown default,在default前增加@unknown,Swift会警告我们有未实现的case。

func PrintError(err:ErrorTest) {
    switch err { // ⚠️Switch must be exhaustive
    case .Error1:
        print("error1")
    case .Error2:
        print("error2")
    @unknown default:
        print("other")
    }
}

2.6 Flattening nested optionals resulting from try? (使用try?时,压缩可选值结果)

使用项目中的例子

struct User {
    var id: Int
    
    init?(id: Int) {
        if id < 1 {
            return nil
        }
        
        self.id = id
    }
    
    func getMessages() throws -> String {
        // complicated code here
        return "No messages"
    }
}
 
let user = User(id: 1)
let messages = try? user?.getMessages()

在Swift4.2的版本,messages的类型为String??,由于user是User?的类型,所以在调用try?时,会导致这一结果,但这往往不是程序需要的结果。

而在Swift5.0的版本,messages的类型为String?,try?对这个结果进行了优化,会压缩嵌套的可选型。

2.7 Checking for integer multiples(int倍数检查)

Swift增加了一个新的函数用于检查a是否为b的倍数,以往我们都是用%(求模)来实现这一功能的

let number = 10

//new
if number.isMultiple(of: 5) {
    print("Yes")
}

//old
if number%5 == 0 {
    print("Yes")
}

2.8 Transforming and unwrapping dictionary values with compactMapValues() (Dictionary. compactMapValues方法)

compactMapValues结合了compactMap方法(过滤非空)和 mapValues(值转换),将dictionary的value转换成新类型的newVaule,并且过滤转换结果为nil的pair。

let dic = [
    "a": "11",
    "b": "22",
    "c": nil,
    "d": "String"
]


let result = dic.compactMapValues { (str) -> Int? in
    guard let safeStr = str else {
        return nil
    }
    return Int.init(safeStr)
}

print(result)

输出:["b": 22, "a": 11]
其中"c":nil由于value为nil,被过滤掉,"d":"String",由于"String"转换Int失败后为nil,所以也被过滤掉。

你可能感兴趣的:(Swift5.0更新内容)