I'm not looking for an answer like how to do it correctly but why this happens.
Here is the code:
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)
I understand in the first if
loop, the param
is casted to Int
and then print out 1
.
But why in second if
loop, if value is Int
is true and then print out 1.2
?
well, it seems that it if you do the following:
it will print "I'm a double" for all three and "I'm an int" for all three as well. It seems that when it goes to the if statement it bridges value to NSNumber, which will be true for any NSNumber type.
However, let's say you do the following:
since String is not of type NSNumber, it will skip and go to the if value is Int, which is of type NSNumber and return the value.
Take a look at https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html, specifically:
We can see this in action in a Playground:
In your
b
case,let value = param
bridgesvalue
to anNSNumber
type. ForNSNumber
,value is Int
will always be true.For unbridged values:
This answer assumes Foundation has been imported. Without Foundation, your assignments will fail.