Calling a Swift class factory method with leading dot notation?

前端 未结 3 1655
甜味超标
甜味超标 2020-11-30 04:40

In a recent question, the poster had this interesting line of code:

self.view.backgroundColor = .whiteColor()

I was surprised to see this.

3条回答
  •  抹茶落季
    2020-11-30 05:14

    I could not find anything along the lines in the documentation. However, the way it works, I believe, is that Swift knows which type is being in context from self.view.backgroundColor, therefore expression starting directly with a dot should be a static on that type (either a static method or static property).

    The following works nicely:

    struct Foo {
        static func fooMethod() -> Foo {
            return Foo()
        }
    
        static var fooProperty: Foo = Foo()
    }
    
    var foo: Foo
    
    foo = .fooMethod()
    
    foo = .fooProperty
    

提交回复
热议问题