1

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
Community
  • 1
  • 1
Guig
  • 9,891
  • 7
  • 64
  • 126
  • Compare [AnyObject not working in Xcode8 beta6?](http://stackoverflow.com/questions/39033194/anyobject-not-working-in-xcode8-beta6) (dupe?) – *everything* is bridgable to `AnyObject` in Swift 3. – Hamish Mar 23 '17 at 00:07
  • Also see a related question asked earlier today: http://stackoverflow.com/questions/42953770/how-can-this-anyobject-return-as-anyobject – rmaddy Mar 23 '17 at 00:11
  • Ah yeah looks like a dupe. I could not find the question so thanks! – Guig Mar 23 '17 at 00:21

0 Answers0