Reference type check

Very good point. I was wrong, @tera I now agree with this statement:

However, I maintain that "reference type" vs "value type" is not the important distinction to be focusing on, rather "reference semantics" vs "value semantics".

In general case it would be impossible to check if the given thing has a value or reference semantics:

struct Nasty {
    private var intValue = 0
    let reference: NSMutableString
    
    var value: Int {
        get {
            if veryComplexCondition() {
                return reference.integerValue
            } else {
                return intValue
            }
        }
        set {
            if veryComplexCondition() {
                reference.setString("\(newValue)")
            } else {
                intValue = newValue
            }
        }
    }
}

You can trust the "thing" documentation and pray it's correct.

2 Likes

I don’t want to generally disagree with you, but there are cases that it matters. The only time I’ve used type(of: foo) is AnyClass is to assert that before assigning it to a weak var foo: AnyObject?, because using a struct/tuple/enum like that will immediately become nil, even if it has reference semantics.

I wonder why would you use AnyObject here instead of a stricter type?

(Fair warning that I don’t have a compiler in front of me and I’m typing this on my phone.)

I don’t want to get too deep into the use case, but let’s just say that I have an array whose member type is like this:

protocol Element {
  var type: Any.Type { get }
  var value: /* some protocol that’s adopted by a WeakBox-like type, but also other things */ { get }
}

I use the type property to determine the type of the value held; I can’t use an associated type because then Swift doesn’t like me accessing the properties (even the marker property type itself) without already knowing what the associated type is.