Swift 5.4

2021-08-19  本文已影响0人  幸运者_Lucky
1. 方法使用不定长参数
func twoVarargs(_ a: Int..., b: Int...) { }
twoVarargs(1, 2, 3, b: 4, 5, 6)
2. 完善隐士语法
let milky: UIColor = .white.withAlphaComponent(0.5)
let milky2: UIColor = .init(named: "white")!.withAlphaComponent(0.5)
let milkyChance: UIColor? = .init(named: "white")?.withAlphaComponent(0.5)

struct Foo {
    static var foo = Foo()
    
    var anotherFoo: Foo { Foo() }
    func getFoo() -> Foo { Foo() }
    var optionalFoo: Foo? { Foo() }
    var fooFunc: () -> Foo { { Foo() } }
    var optionalFooFunc: () -> Foo? { { Foo() } }
    var fooFuncOptional: (() -> Foo)? { { Foo() } }
    subscript() -> Foo { Foo() }
}

let _: Foo = .foo.anotherFoo
let _: Foo = .foo.anotherFoo.anotherFoo.anotherFoo.anotherFoo
let _: Foo = .foo.getFoo()
let _: Foo = .foo.optionalFoo!.getFoo()
let _: Foo = .foo.fooFunc()
let _: Foo = .foo.optionalFooFunc()!
let _: Foo = .foo.fooFuncOptional!()
let _: Foo = .foo.optionalFoo!
let _: Foo = .foo[]
let _: Foo = .foo.anotherFoo[]
let _: Foo = .foo.fooFuncOptional!()[]

struct Bar {
    var anotherFoo = Foo()
}

extension Foo {
    static var bar = Bar()
    var anotherBar: Bar { Bar() }
}

let _: Foo = .bar.anotherFoo
let _: Foo = .foo.anotherBar.anotherFoo

3. result builders 之前叫 function builders

理解SwiftUI 中 Stack 的使用,就理解了 result builders

struct TaskAction {
    init(action: () -> Void) {
        action()
    }
}


@resultBuilder
struct SyncTasksBuilder {
    static func buildBlock(_ actions: TaskAction...) -> [TaskAction] {
        actions
    }
}

class SyncTasks {
    
    static func awaitTasks(@SyncTasksBuilder _ content: () -> [TaskAction]) {
        DispatchQueue.global().sync {
            _ = content()
        }
    }
}
// 使用
SyncTasks.awaitTasks {
    TaskAction {
        sleep(4)
        print("action1")
    }
    
    TaskAction {
        print("action2")
    }
}
4. 局部方法重载
func makeCookies2() {   
    add(item: Butter())
    add(item: Flour())
    add(item: Sugar())

    func add(item: Butter) {
        print("Adding butter…")
    }

    func add(item: Flour) {
        print("Adding flour…")
    }

    func add(item: Sugar) {
        print("Adding sugar…")
    }
}

makeCookies2()
5. 局部变量支持属性包装
@propertyWrapper struct NonNegative<T: Numeric & Comparable> {
    var value: T

    var wrappedValue: T {
        get { value }

        set {
            if newValue < 0 {
                value = 0
            } else {
                value = newValue
            }
        }
    }

    init(wrappedValue: T) {
        if wrappedValue < 0 {
            self.value = 0
        } else {
            self.value = wrappedValue
        }
    }
}

func playGame() {
    @NonNegative var score = 0

    // player was correct
    score += 4

    // player was correct again
    score += 8

    // player got one wrong
    score -= 15

    // player got another one wrong
    score -= 16

    print(score)
}
上一篇下一篇

猜你喜欢

热点阅读