【问题标题】:isMemberOfClass in SwiftSwift 中的 isMemberOfClass
【发布时间】:2017-01-13 20:17:17
【问题描述】:

关键字is等价于isKindOfClass

但我无法在 swift 中找到与 isMemberOfClass 等效的内容。

注意: 我的问题不是关于 isKindOfClassisMemberofclass 之间的区别,而是关于 Swift 中 isMemberofClass 的等价物

有人请澄清

【问题讨论】:

标签: ios swift


【解决方案1】:

您正在寻找 type(of:)(之前在 Swift 2 中为 .dynamicType)。

例子:

class Animal {}
class Dog : Animal {}
class Cat : Animal {}

let c = Cat()

c is Dog // false
c is Cat // true
c is Animal // true

// In Swift 3:
type(of: c) == Cat.self // true
type(of: c) == Animal.self // false

// In Swift 2:
c.dynamicType == Cat.self // true
c.dynamicType == Animal.self // false

【讨论】:

  • 使用未解析的标识符type 会抛出错误
  • 你正在使用 Swift 2。在 Swift 3 中它是 type(of: c) 在 Swift 1 和 2 中它是 c.dynamicType
  • 谢谢你拯救了我的一天!
【解决方案2】:

如果是可选变量type(of:),则返回初始化的类型。

例子:

class Animal {}
class Cat : Animal {}

var c: Animal?
c = Cat()

type(of: c) // _expr_63.Animal>.Type
type(of: c) == Cat?.self // false
type(of: c) == Animal?.self // true

我的类继承自NSObject,所以我使用了它的变量classForCoder,它对我有用。

class Animal : NSObject {}
class Cat : Animal {}

var c: Animal?
c = Cat()
c?.classForCoder == Cat.self // true

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2014-07-24
    相关资源
    最近更新 更多