Swift 5.1新增特性



  • 新增特性

    • SE-0242 Massive improvements to synthesized memberwise initializers
    • SE-0255 Implicit returns from single-expression functions
    • SE-0068 Universal Self
    • SE-0244 Opaque return types
    • SE-0254 Static and class subscripts
    • SE-0240 Ordered collection diffing
    • SE-0245 Creating uninitialized arrays

    介绍

    SE-0242 Massive improvements to synthesized memberwise initializers

    对于 struct 来说,Swift 5.1 将强化自动生成 struct 初始化的方法。因为 age 有默认初始值,所以初始化方法中可忽略 age 参数而直接使用默认值。

    • 示例
    struct User {
        var name: String
        var age: Int = 18
    }
    
    let user1 = User(name: "Lily", age: 18)
    let user2 = User(name: "Han")
    

    SE-0255 Implicit returns from single-expression functions

    Swift 5.1 中,方法返回值可以省略 return 关键字。

    • 示例
    func getNum(_ num: Int) -> Int {
        num * 10
    }
    

    SE-0068 Universal Self

    Swift 5.1 拓展了 Self 的使用。

    比如以下代码,最终将输出 "Maximum network requests: 4.",但其实我们是希望 ThrottledNetworkManager 可以覆写 maximumActiveRequests 值的,。

    class NetworkManager {
        class var maximumActiveRequests: Int {
            return 4
        }
    
        func printDebugData() {
            print("Maximum network requests: \(NetworkManager.maximumActiveRequests).")
        }
    }
    
    class ThrottledNetworkManager: NetworkManager {
        override class var maximumActiveRequests: Int {
            return 1
        }
    }
    
    let manager = ThrottledNetworkManager()
    manager.printDebugData()
    

    Swift 5.1 中,可以通过 Self 来改造上面的代码。

    class ImprovedNetworkManager {
        class var maximumActiveRequests: Int {
            return 4
        }
    
        func printDebugData() {
            print("Maximum network requests: \(Self.maximumActiveRequests).")
        }
    }
    
    class ThrottledNetworkManager: ImprovedNetworkManager {
        override class var maximumActiveRequests: Int {
            return 1
        }
    }
    
    let manager = ThrottledNetworkManager()
    manager.printDebugData()
    

    输出

    Maximum network requests: 1.
    

    意味着在子类中 Self 实际指向的是子类。


    SE-0244 Opaque return types

    Swift 5.1 中,允许 func 通过关键字 some 来修饰一个返回值类型,最终以运行时返回的类型作为实际类型。

    // some 特性
    protocol IBase {}
    
    class A: IBase {}
    
    class B: IBase {}
    
    func testA() -> some IBase {
        return A()
    }
    
    func testB() -> some IBase {
        return B()
    }
    
    let a = testA()
    let b = testB()
    print(type(of: a))
    print(type(of: b))
    

    输出

    A
    B
    

    SE-0254 Static and class subscripts

    static 和 class 类型支持下标操作。

    • 示例
    public enum NewSettings {
        private static var values = [String: String]()
        
        public static subscript(_ name: String) -> String? {
            get {
                return values[name]
            }
            set {
                values[name] = newValue
            }
        }
    }
    
    NewSettings["Username"] = "John"
    print(NewSettings["Username"] ?? "Unknown")
    

    输出

    John
    

    SE-0240 Ordered collection diffing

    Swift 5.1 引入了在有序集合之间计算和应用差异的能力。

    • 示例
    var scores1 = [100, 91, 95, 98, 100]
    let scores2 = [100, 98, 95, 91, 100]
    
    let diff = scores2.difference(from: scores1)
    
    var scoreRemoved: [Int] = []
    var scoreInsert: [Int] = []
    
    for item in diff {
        switch item {
        case .remove(let offset, let element, _):
            print("remove offset = \(offset), element = \(element)")
            scores1.remove(at: offset)
        case .insert(let offset, let element, _):
            print("insert offset = \(offset), element = \(element)")
            scores1.insert(element, at: offset)
        }
    }
    
    print(scores1)
    

    输出

    remove offset = 2, element = 95
    remove offset = 1, element = 91
    insert offset = 2, element = 95
    insert offset = 3, element = 91
    scores1 = [100, 98, 95, 91, 100]
    

    SE-0245 Creating uninitialized arrays

    Swift 5.1 中,可以创建一个未初始化的数组。

    • 示例

    创建一个 capacity 为 10 的数组,并手动进行初始化操作。

    let randomNumbers = Array<Int>(unsafeUninitializedCapacity: 10) { buffer, initializedCount in
        for x in 0..<10 {
            buffer[x] = Int.random(in: 0...10)
        }
    
        initializedCount = 10
    }
    

    相关

    更多讯息,可关注微信公众号:SwiftMic

    微信公众号推广Logo_min.png


Log in to reply