标题不是最佳,建议欢迎
Bool
和数字值有点麻烦。我想确定AnyObject
(来自JSON)是Bool
还是数字。
所以我需要一个只有插入的类型真的是Bool
或数字才能成功的测试。现在它会自动转换,所有陈述都是真的。
let some : AnyObject = 1
if some is Bool {
print("is Bool", some as! Bool)
}
if some is Int {
print("is Int", some as! Int)
}
let some2 : AnyObject = false
if some2 is Bool {
print("is Bool", some2 as! Bool)
}
if some2 is Int {
print("is Int", some2 as! Int)
}
let some3 : AnyObject = 1.1
if some3 is Bool {
print("is Bool", some3 as! Bool)
}
if some3 is Int {
print("is Int", some3 as! Int)
}
答案 0 :(得分:1)
1
,1.0
,true
,所有类型都桥接到NSNumber
您可以查看objCType
let some : AnyObject = true
if let type = String.fromCString(some.objCType) {
switch type {
case "c" : print("is Bool", some as! Bool)
case "q" : print("is Int", some as! Int)
case "d" : print("is Double", some as! Double)
default : print("no idea")
}
} else {
print("no matching objCType")
}