swift - 如何在swift中获取变量的类型

标签 swift

<分区>

swift 中的每个变量都有一个类型。

var c: Int = 0//类型是 Int

var d: (Int,(String,Double))//类型是 (Int,(String,Double))

我怎样才能得到一个变量的类型。请参见下面的示例。

func retSomeThing ()-> ((Int,(String,b: Int))){
    return(10,("something",b: 56))
}

var a = retSomeThing()
var b = retSomeThing()
if (a.type.equal(b.type)) { // my problem is here.
    print("Hala Madrid")
}

我用过这段代码

a.dynamicType

但它显示:元组类型 '(Int, (String, b: Int))' 的值没有成员 'dynamicType'

最佳答案

您可以使用 is 关键字检查任何变量的类型。

var a = 0
var b = "demo"
if (a is Int) { 
    print("It's an Int")
}

if (b is String) { 
    print("It's a String")
}

要比较任何复杂类型,您可以使用以下方法:

if type(of: abc) == type(of: def) {
    print("matching type")
} else {
    print("something else")
}

关于swift - 如何在swift中获取变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44085669/

相关文章:

ios - 实例成员不能用于类型 'ViewController'

ios - Swift:避免强制展开常量变量

ios - 从 Controller 外部快速重新加载 collectionView 上的数据

ios - 使用 TableView 从 ControlView 获取字符串

ios - Swift 面向协议(protocol)编程 : Can Protocol Extension Property Have Same Name As Base Class Property

ios - 针对 iPhone 中的不同屏幕改变 UITextFields 的高度和间距

实现协议(protocol)类型的swift方法参数?

ios - 从 CloudKit 获取不在设备上的记录的任何(或最佳)方法?

ios - 工作区包括 pod 安装和成功构建后丢失的文件

ios - 如何在 GitHub for iOS (SWIFT) 项目中隐藏 API key ?