Why is casting a struct to AnyObject not a compile error in swift?

后端 未结 1 1203
北荒
北荒 2020-12-11 17:16

The code below compiles and works in swift.

struct TestStruct {
    let value: String = \"asdf\"
}

func iWantARefe         


        
相关标签:
1条回答
  • 2020-12-11 18:02

    This is a feature to facilitate passing to Cocoa. Any struct can be wrapped into a SwiftValue reference type. If you print type(of: object) you'll see the wrapper.

    I don't think there is any contract for "expecting a reference type." More importantly, while "value types" and "reference types" exist in Swift, what really matter is value and reference semantics, which are not expressible in the language. You can create value semantics in reference types and reference semantics in value types, so the Swift type system really isn't of any help in that regard.

    The important point here is that you only get this unusual behavior if you explicitly request it by asking for as AnyObject. There are very few reason to write that, and if you are, you had better know exactly what you're doing.

    0 讨论(0)
提交回复
热议问题