2

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

enter image description here

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

Community
  • 1
  • 1
Nuzhdin Vladimir
  • 1,714
  • 18
  • 36
  • 2
    Compare [AnyObject not working in Xcode8 beta6?](http://stackoverflow.com/q/39033194/2976878) (dupe?) – *everything* is bridgeable to `AnyObject` in Swift 3. Things that cannot be directly represented in Obj-C (such as `MyStruct`) are put into an opaque Obj-C compatible box, `_SwiftValue`. A `weak` reference to this should be fine – although because in your example you're doing the boxing in the assignment, it'll be deallocated immediately. – Hamish Apr 05 '17 at 13:05

1 Answers1

1

The short answer is:

type(of: value) is AnyClass
Nuzhdin Vladimir
  • 1,714
  • 18
  • 36