Swift - 结构和AnyObject

时间:2017-03-23 00:02:11

标签: swift anyobject swift-structs

我认为结构不是AnyObject。例如:https://stackoverflow.com/a/33921992/2054629

但后来我尝试了(在swift 3中,xcode 8.2.1):

struct Struct{
  let foo = 1
}
let s = Struct()
s is AnyObject // true, and I get a warning saying "'is' test is always true"

我确实能做到:

let o = s as AnyObject
(o as! Struct).foo // this is 1

那么struct是AnyObject吗?也许不是:

class Weak<T: AnyObject> {
  public weak var value : T?
  public init (value: T) {
    self.value = value
  }
}

let weak = Weak<Struct>(value: s) // Error: "Type 'Struct' does not conform to protocol 'AnyObject'"

现在,如果相反,我将最后一行替换为:

let weak = Weak<AnyObject>(value: s as AnyObject)

编译好。事实上,我们s is AnyObject确实如此。 但是接下来

weak.value // is nil

发生了什么事?

如果你需要玩游戏,这是完整的代码:

struct Struct {}
let s = Struct()
s is AnyObject
let o = s as AnyObject
(o as! Struct).foo

class Weak<T: AnyObject> {
  public weak var value : T?
  public init (value: T) {
    self.value = value
  }
}

// let weak = Weak<Struct>(value: s)
let weak = Weak<AnyObject>(value: s as AnyObject)
weak.value

0 个答案:

没有答案