【问题标题】:Call static method without repeating the class name调用静态方法而不重复类名
【发布时间】:2018-09-19 15:32:07
【问题描述】:

是否可以在 Swift 中调用static(或class)方法/属性而不编写类名(来自实例方法)?

class Foo {
  class func someValue() -> Int {
    return 1337
  }

  func printValue() {
    print(Foo.someValue())
    print(type(of: self).someValue())

    print(Self.someValue()) // error: use of unresolved identifier 'Self'
  }
}

到目前为止,我已经找到了一种使用协议/类型别名的解决方法:

protocol _Static {
  typealias Static = Self
}


class Foo: _Static {
  class func someValue() -> Int {
    return 1337
  }

  func printValue() {
    print(Static.someValue()) // 1337
  }
}

但我想知道是否有更好的方法来做到这一点?

【问题讨论】:

标签: swift


【解决方案1】:

在 Swift 5.1 中,此代码不再产生错误。

class Foo {
  class func someValue() -> Int {
    return 1337
  }

  func printValue() {
    print(Foo.someValue())
    print(type(of: self).someValue())

    print(Self.someValue()) // ok
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2011-12-11
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多