Check for value or reference type in Swift
Asked Answered
I

2

6

How can we check if a parameter passed in a function is a value or a reference type? For example

func isReferenceType(toTest: Any) {
    return true // or false
}

As we see here, we are not able to do this leveraging generics.

Itemized answered 11/1, 2016 at 15:39 Comment(3)
I haven't tried, but doesn't solution no. 2 in the link that you posted work for you?Godbey
What about is AnyObject?Whippletree
For Swift 3 and Xcode 8 - https://mcmap.net/q/455613/-anyobject-not-working-in-xcode8-beta6Charissacharisse
C
7

AnyObject is a protocol that any class type automatically conforms to, so you can write:

func isReferenceType(toTest: Any) -> Bool {
    return toTest.dynamicType is AnyObject
}

class Foo { }
struct Bar { }

isReferenceType(Foo())    // true
isReferenceType(Bar())    // false
isReferenceType("foo")    // false
isReferenceType(123)      // false
isReferenceType([1,2,3])  // false
Circumgyration answered 11/1, 2016 at 15:48 Comment(3)
Yes, but isReferenceType("foo") or isReferenceType(123) or isReferenceType([1, 2, 3]) will also return true (if Foundation is imported).Banda
Ah, the old silent cast. Checking the dynamic type instead of the value itself seems to resolve that...Circumgyration
Or alternatively: func isReferenceType<T: Any>(toTest: T) -> Bool { return !(T.self is AnyObject) }Itemized
I
5

Swift 5

func isReferenceType(_ toTest: Any) -> Bool {
    return type(of: toTest) is AnyClass
}
Irishman answered 13/5, 2020 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.