gpt4 book ai didi

Swift 类型推断和类型检查问题

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:14 26 4
gpt4 key购买 nike

我不是在寻找答案,比如如何正确地做到这一点,而是为什么会发生这种情况。

代码如下:

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)

我理解在第一个 if 循环中,param 被转换为 Int 然后打印出 1 .

但是为什么在第二个if循环中,if value is Int为真然后打印出1.2

最佳答案

看看https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html ,具体来说:

Instances of the Swift numeric structure types, such as Int, UInt, Float, Double, and Bool, cannot be represented by the AnyObject type, because AnyObject only represents instances of a class type. However, when bridging to Foundation is enabled, Swift numeric values can be assigned to constants and variables of AnyObject type as bridged instances of the NSNumber class.

我们可以在 Playground 中看到这一点:

let value = 1.2
value.dynamicType //Double.Type
value is Int //false
let castValue = value as AnyObject
castValue.dynamicType //__NSCFNumber.Type (a private framework class, part of the NSNumber class cluster)
//NSNumber is bridged to Int, UInt, Float, Double, and Bool so `is` tests for those types will return `true`
castValue is Int //true
castValue is Float //true
//NSNumber is not bridged to String so an `is` test will return `false`
castValue is String //false

关于Swift 类型推断和类型检查问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35047451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com