Swift 3 - How to write functions with no initialisers like the new UIColors?

前端 未结 6 605
再見小時候
再見小時候 2021-01-18 17:31

In previous versions of swift, you would get the colour white like this UIColor.whiteColor()

However, in Swift 3, you get the colour white without initi

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 17:55

    When the compiler can infer the type of the value you are going to need, like here

    let a: Foo = ...
    

    you can use a static member (method, function, stored property, computed property) omitting the name of the type.

    So given this type

    class Foo {
        static let a = Foo()
        static var b = Foo()
        static var c:Foo { return Foo() }
        static func d() -> Foo { return Foo() }
    }
    

    you can write

    let a: Foo = .a
    let b: Foo = .b
    let c: Foo = .c
    let d: Foo = .d()
    

    The same technique can be used when you pass a value to a function

    func doNothing(foo: Foo) { }
    

    Again the type of the parameter can be inferred by the compiler so instead of writing

    doNothing(foo: Foo.a)
    

    you can simply write

    doNothing(foo: .a)
    

提交回复
热议问题