How to understand if instance is value type or reference type?
DESCRIPTION:
First of all, I've read about AnyObject in the documentation.
Swift provides two special types for working with nonspecific types:
Any can represent an instance of any type at all, including function types.:
AnyObject can represent an instance of any class type.
Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.
So I've decided to write some simple code in my Playground:
struct MyStruct {
var x = 5
}
let testStruct = MyStruct()
testStruct is AnyObject
if let object = testStruct as? AnyObject {
//Do something
}
And I was shocked when saw 2 warnings.
- 'is' test is always true
- Conditional cast from 'MyStruct' to 'AnyObject' always succeedstestStruct is AnyObject
Even more... I was able to set my struct to the weak property.
class TestClass {
weak var object: AnyObject?
}
var instance: TestClass? = TestClass()
instance?.object = testStruct as AnyObject
And I haven't seen any warnings or errors there. Will it cause crash or undefined behavior? It looks strange for me...
Also I mentioned types in the playground.
- type(of: testStruct as AnyObject) - _SwiftValue.Type
- type(of: testStruct) - MyStruct.Type
Probably testStruct was implicitly converted to class. But I'm not sure bout it, and can't any info about it on the internet =(
Have you ever read something about it? Or can you give me some link to the documentation to understand what is going on. Probably I missed very something very important.
- Swift version: Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
- XCode version: 8.2.1 (8C1002)
P.S.
I have to emphasis that it works fine(as I think) in Swift 2.0.
Any way thanks for attention