【问题标题】:Calling a Swift class factory method with leading dot notation?使用前导点表示法调用 Swift 类工厂方法?
【发布时间】:2020-07-14 18:53:14
【问题描述】:

在最近的一个问题中,发帖者有这样一段有趣的代码:

self.view.backgroundColor = .whiteColor()

看到这个我很惊讶。我只见过用于枚举值的 前导点 表示法。在这种情况下,backgroundColorUIColor? 类型,whiteColorUIColor 上的类方法,它返回 UIColor

为什么会这样?这是调用工厂方法的合法方式吗?

【问题讨论】:

    标签: swift


    【解决方案1】:

    这个功能被称为“Implicit Member Expression

    隐式成员表达式是在类型推断可以确定隐含类型的上下文中访问类型成员的缩写方式,例如枚举案例或类方法。它具有以下形式:

    .会员名


    但是,就目前而言,我建议您不应该OptionalImplicitlyUnwrappedOptional 上下文中使用此功能。

    虽然这可行:

    // store in Optional variable
    let col: UIColor?
    col = .redColor()
    
    // pass to function
    func f(arg:UIColor?) { println(arg) }
    f(.redColor())
    

    这会使编译器崩溃:(

    func f(arg:UIColor?, arg2:Int) { println(arg) }
    //                 ^^^^^^^^^^ just added this.
    f(.redColor(), 1)
    

    编译器有一些错误。见:does swift not allow initialization in function parameters?

    【讨论】:

    • 应该注意的是,至少在 Swift 3.2 中,最后一个示例 not 会使编译器崩溃,实际上(在插入省略的参数标签之后)运行得很好.
    【解决方案2】:

    看起来规则是:如果一个类型有一个返回该类型的静态方法,如果返回类型已经确定,你可以跳过该类型的名称:

    struct S {
        static func staticmethod() -> S {
            return S()
        }
        static var staticproperty: S {
            return S()
        }
    }
    
    let s1: S = .staticmethod()
    let s2: S = .staticproperty
    

    我想知道这是故意的,还是 Enums 实现的副作用,考虑到这个特性,它可能被认为是这样的语法糖:

    struct FakeEnum {
        let raw: Int
        static var FirstCase:  FakeEnum  { return FakeEnum(raw: 0) }
        static var SecondCase: FakeEnum  { return FakeEnum(raw: 1) }
    }
    
    let e: FakeEnum = .FirstCase
    

    【讨论】:

      【解决方案3】:

      我在文档中找不到任何内容。但是,我相信它的工作方式是 Swift 从self.view.backgroundColor 知道上下文中的类型,因此直接以点开头的表达式应该是该类型的静态(静态方法或静态属性)。

      以下效果很好:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多