如何在 Swift 中确定变量的类型 [英] How to determine the type of a variable in Swift
问题描述
Swift 中是否有确定变量类型的函数?我认为 Python 中可能有类似 type()
之类的东西.
Is there a function to determine the variable type in Swift? I presume there might be something like like type()
in Python.
我想要一种方法来判断一个变量是 Swift 中的 Foundation 对象还是 C 变量.像 NSString 与字符串,或 NSArray 与数组.这样我就可以在控制台中注销它并清楚地看到它是什么.
I'd like a way to judge if a variable is a Foundation object or C variable in Swift. Like NSString vs String, or NSArray vs array. So that I can log it out in console and see clearly what it is.
例如,我想知道为下面的第一个 array
推断的类型:
For example, I would like to know the type inferred for the the first array
below:
var array = [1,2,3] // by default NSArray or array?
var array:[Int] = [1,2,3]
var array:NSArray = [1,2,3]
var array:Array<Any> = [1,2,3]
我在 这个问题,但我会说这与我想问的完全不同.
I have seen answers for judging if a given variable is a kind of given type in this question, but I'll say it's quite different from what I want to ask.
推荐答案
您可以使用 .dynamicType
属性获取对值的类型对象的引用.这相当于 Python 的 type()
函数,并在 在语言参考下的 Swift 文档:类型:元类型类型.
You can get a reference to the type object of a value by using the .dynamicType
property. This is equivalent to Python's type()
function, and is mentioned in the Swift documentation under Language Reference: Types: Metatype Type.
var intArray = [1, 2, 3]
let typeOfArray = intArray.dynamicType
使用这个类型对象,我们可以创建一个相同数组类型的新实例.
With this type object, we are able to create a new instance of the same array type.
var newArray = typeOfArray()
newArray.append(5)
newArray.append(6)
println(newArray)
[5, 6]
通过尝试附加一个浮点数,我们可以看到这个新值是相同的类型([Int]
):
We can see that this new value is of the same type ([Int]
) by attempting to append a float:
newArray.append(1.5)
error: type 'Int' does not conform to protocol 'FloatLiteralConvertible'
如果我们导入 Cocoa 并使用混合类型的数组字面量,我们可以看到创建了一个 NSArray
:
If we import Cocoa and use an array literal with mixed types, we can see that an NSArray
is created:
import Cocoa
var mixedArray = [1, "2"]
let mixedArrayType = mixedArray.dynamicType
var newArray = mixedArrayType()
var mutableArray = newArray.mutableCopy() as NSMutableArray
mutableArray.addObject(1)
mutableArray.addObject(1.5)
mutableArray.addObject("2")
println(mutableArray)
(1, "1.5", 2)
但是,此时似乎没有任何通用方法来生成类型对象的字符串描述,因此这可能无法起到您所询问的调试作用.
However, at this point there does not seem to be any general way to generate a string description of a type object, so this may not serve the debugging role that you were asking about.
从 NSObject
派生的类型确实有一个 .description()
方法,正如使用的 在 SiLo 的回答中,
Types derived from NSObject
do have a .description()
method, as is used in SiLo's answer,
println(mixedArrayType.description())
__NSArrayI
然而,这并不存在于诸如 Swift 的内置数组之类的类型上.
However this is not present on types such as Swift's built-in arrays.
println(typeOfArray.description())
error: '[Int].Type' does not have a member named 'description'
这篇关于如何在 Swift 中确定变量的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!