How to determine the type of a variable in Swift

前端 未结 5 1499
你的背包
你的背包 2020-12-04 21:59

Is there a function to determine the variable type in Swift? I presume there might be something like like type() in Python.

I\'d like a way to judge if

5条回答
  •  天涯浪人
    2020-12-04 22:28

    It is possible to do so, though it's not necessarily that easy nor useful:

    func getClassName(obj : AnyObject) -> String
    {
        let objectClass : AnyClass! = object_getClass(obj)
        let className = objectClass.description()
    
        return className
    }
    
    let swiftArray = [1, 2, 3]
    let swiftDictionary = ["Name": "John Doe"]
    let cocoaArray : NSArray = [10, 20, 30]
    var mutableCocoaArray = NSMutableArray()
    
    println(getClassName(swiftArray))
    println(getClassName(swiftDictionary))
    println(getClassName(cocoaArray))
    println(getClassName(mutableCocoaArray))
    

    Output:

    _TtCSs22ContiguousArrayStorage00007F88D052EF58
    __NSDictionaryM
    __NSArrayI
    __NSArrayM
    

    You are better of using the is and as keywords in Swift. Many foundation classes use class clusters (as you can see with __NSArrayI (immutable) and __NSArrayM (mutable).

    Notice the interesting behavior. The swiftArray defaults to using a Swift Array while the swiftDictionary defaulted to NSMutableDictionary. With this kind of behavior I would not really rely on anything being a certain type (check first).

提交回复
热议问题