I thought that structs were not AnyObject. For instance: https://stackoverflow.com/a/33921992/2054629
But then I tried (in 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"
And indeed I can do:
let o = s as AnyObject
(o as! Struct).foo // this is 1
So struct is AnyObject? Maybe not:
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'"
Now if instead I replace the last line by:
let weak = Weak<AnyObject>(value: s as AnyObject)
that compile fine. Indeed we have s is AnyObject
that is true.
But then
weak.value // is nil
What is going on?
Here is the entire code if you need to play around:
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