agr*_*986 7 reflection swift swift3
这段代码适用于Swift 3:
let a = 1
type(of: a) == Int.self // true
Run Code Online (Sandbox Code Playgroud)
但是,显然这段代码失败了:
// error: binary operator '==' cannot be applied to two 'Int.Type' operands
type(of: 1) == Int.self
Run Code Online (Sandbox Code Playgroud)
如果有的话,第二次比较的语法是什么?
非常感谢.
我认为该错误消息具有误导性。真正的问题是如何解释1
第二次调用中的文字。Int
当你定义一个变量时,Swift 默认为 an :
let a = 1 // a is an Int
Run Code Online (Sandbox Code Playgroud)
但编译器可以根据上下文将其读为Double
、UInt32
、等:CChar
func takeADouble(value: Double) { ... }
func takeAUInt(value: UInt) { ... }
takeADouble(value: 1) // now it's a Double
takeAUInt(value: 1) // now it's a UInt
Run Code Online (Sandbox Code Playgroud)
type(of:)
被定义为通用函数:
func type<Type, Metatype>(of: Type) -> Metatype
Run Code Online (Sandbox Code Playgroud)
编译器不知道如何解释Type
泛型参数:它应该是Int
、UInt
、UInt16
等吗?这是我从 IBM Swift Sandbox 收到的错误:
Overloads for '==' exist with these partially matching parameter lists
(Any.Type?, Any.Type?), (UInt8, UInt8), (Int8, Int8),
(UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), ...
Run Code Online (Sandbox Code Playgroud)
您可以通过告诉编译器它是什么类型来给它一些帮助:
type(of: 1 as Int) == Int.self
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
149 次 |
最近记录: |