Swift"is"运算符,其类型存储在变量中

kar*_*ski 11 types swift

这段代码按预期工作.输出中打印"integer is int".

let integer = Int()

if integer is Int {
    println("integer is int")
}
else {
    println("integer is not int")
}
Run Code Online (Sandbox Code Playgroud)

我想以is与使用isKindOfClass方法相同的方式使用运算符- 将类(或更确切地说类型)存储在变量中.它看起来像这样:

let integer = Int()
let intType : Any = Int.self

if integer is intType {
    println("Integer is int")
}
else {
    println("Integer is not int")
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会产生错误:Use of undeclared type 'IntType'.

IntTypeif条件甚至具有不同的颜色(如果您将其粘贴到操场)比在源代码中的其他地方,这表明(如错误消息指出)其被视为一个类名(如IntType将是一个类).但事实并非如此.这意味着is运算符不能与右侧的变量一起使用?

我想使用is运算符,因为它不仅可以比较类,还可以比较其他类型.

如何检查值是否具有我期望的类型?


我找到了肮脏的解决方案,但它真的远非可靠......

let integer = Int()
let intType : Any = Int.self

func ==(left: Any, right: Any) -> Bool {
    let leftString = "\(left)"
    let rightString = "\(right)"
    return leftString == rightString
}

if (integer.dynamicType as Any) == intType {
    println("true")
}
else {
    println("false")
}
Run Code Online (Sandbox Code Playgroud)

作品很完美,但要小心 - 因为这个也是如此:

if (integer.dynamicType as Any) == ("Swift.Int" as Any) {
    println("true")
}
else {
    println("false")
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?


好的,我会进一步解释我想要实现的目标.我有管理泛型类实例的实例的对象.在某些时候,我需要根据泛型类型选择其中一个泛型类实例.例:

class GenericClass<T> {}

struct ToolInfo {
    let tool : AnyObject
    let jobType : Any
}

class Manager {
    var tools = Array<ToolInfo>()

    func pickToolForTheJob(job : Any) -> AnyObject {
        return tools.magicMethodWhichReturnProperTool()
    }
}

let viewTool = GenericClass<UIView>()
let rectangleTool = GenericClass<CGRect>()

let manager = Manager()
manager.tools.append(ToolInfo(tool: viewTool, jobType: UIView.self))
manager.tools.append(ToolInfo(tool: rectangleTool, jobType: CGRect.self))

manager.pickToolForTheJob(UIView()) // i want to get viewTool here
manager.pickToolForTheJob(CGRect()) // i want to get rectangleTool here
Run Code Online (Sandbox Code Playgroud)

目前我有ToolInfostruct,因为据我所知,<>在实例化泛型类对象时不可能传入类型.但我还是无法比较它.

mat*_*att 6

这意味着运算符不能与右侧的变量一起使用吗?

正确.右侧is必须在编译时进行硬编码.

如果您不需要多态,并且您的类型是类类型,则可以使用它===来比较dynamicType实例和类类型.这是你在纯Swift的右侧获得一个变量类型的唯一方法.