问题描述
我不是在寻找正确答案,但为什么会发生这种情况。
I'm not looking for an answer like how to do it correctly but why this happens.
这是代码:
func isInt(param: AnyObject?) {
if let value = param as? Int {
print(value)
} else {
print("Not Int")
}
if let value = param {
if value is Int {
print(value)
} else {
print("Not Int")
}
}
}
let a:AnyObject? = 1.2
let b:Float? = 1.2
let c:Double? = 1.2
isInt(a)
isInt(b)
isInt(c)
我理解在第一个如果
循环中, param
被转换为 Int
然后打印出 1
。
I understand in the first if
loop, the param
is casted to Int
and then print out 1
.
如果
循环,如果值为Int
为true,然后打印出 1.2
But why in second if
loop, if value is Int
is true and then print out 1.2
?
推荐答案
在 b
$ c> let value = param bridges value
到 NSNumber
类型。 NSNumber
,值为Int
将始终为真。
In your b
case, let value = param
bridges value
to an NSNumber
type. For NSNumber
, value is Int
will always be true.
对于unbridged值:
For unbridged values:
a is Int // always true, AnyObject bridges to NSNumber here
b is Int // false, cast from Float to Int always fails
c is Int // false, cast from Double to Int always fails
b $ b
这个答案假设Foundation已经导入。没有基金会,您的作业将失败。
This answer assumes Foundation has been imported. Without Foundation, your assignments will fail.
这篇关于Swift类型推理和类型检查问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!