Check for value or reference type in Swift

后端 未结 2 1858
死守一世寂寞
死守一世寂寞 2021-01-03 03:59

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 fa         


        
相关标签:
2条回答
  • 2021-01-03 04:51

    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
    
    0 讨论(0)
  • 2021-01-03 04:53

    Swift 5

    func isReferenceType(_ toTest: Any) -> Bool {
        return type(of: toTest) is AnyClass
    }
    
    0 讨论(0)
提交回复
热议问题