1
struct AStruct {
    var aValue: Int
}
let aStruct = AStruct(aValue: 3)
let aClass = aStruct as AnyObject  //Why does this line compile?
let ident = ObjectIdentifier(aClass)  //`ObjectIdentifier()` requires a reference object, but this code works

In the code above, I'm casting a struct, which is a value type, to AnyObject (for class objects) and it works.

I would expect a compile error on that line.

In the next line I'm passing the struct, cast to AnyObject to ObjectIdentifier(), which requires that it's parameter be a class object. That code runs, and returns a result. I would expect that line to crash at runtime if it was passed an Any.

What the @#$@#?

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    Possible duplicate of https://stackoverflow.com/questions/39033194/anyobject-not-working-in-xcode8-beta6: *"... is/as AnyObject always succeed for all types now. It's behaving as intended."* – Martin R Nov 09 '18 at 18:44
  • Since Swift 3, Swift introduce a type named `_SwiftValue` and `as AnyObject` has become an always-success conversion. Pure Swift values are converted to `_SwiftValue`, which is a reference type. – OOPer Nov 09 '18 at 18:46
  • `type(of: aClass)` confirms that it is `__C._SwiftValue.Type`. Have a look [here](https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftValue.h). – ielyamani Nov 09 '18 at 19:45
  • Maybe you want to [check](https://stackoverflow.com/a/53136944/2907715) first? – ielyamani Nov 09 '18 at 19:51

0 Answers0