斯威夫特“是"类型存储在变量中的运算符 [英] Swift "is" operator with type stored in variable

查看:21
本文介绍了斯威夫特“是"类型存储在变量中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码按预期工作.在输出中打印整数是整数".

This piece of code works as expected. "integer is int" is printed in output.

let integer = Int()

if integer is Int {
    println("integer is int")
}
else {
    println("integer is not int")
}

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

I want to use is operator in the same way as I can use isKindOfClass method - with class (or rather type) stored in variable. It would look like this:

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

if integer is intType {
    println("Integer is int")
}
else {
    println("Integer is not int")
}

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

Unfortunately this produce an error: Use of undeclared type 'IntType'.

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

IntType in if condition has even a different color (if you paste it to playground) than in other places in source code, suggesting that (as the error message says) its being treated as a class name (like IntType would be a class). But it isn't. It means that is operator cannot be used with variables on the right side?

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

I want to use is operator because it can compare not only classes, but also other types.

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

How can I check if value has type which I expect?

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

I found dirty solution, but it's really far from being reliable...

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")
}

工作完美,但要小心 - 因为这也是正确的:

Works perfect, but be careful - cause this one is also true:

if (integer.dynamicType as Any) == ("Swift.Int" as Any) {
    println("true")
}
else {
    println("false")
}

有没有更好的方法?

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

Ok, I'll explain further what do I want to achieve. I have object which manages instances of generic class instances. At some point I need to pick one of those generic class instances basing on type of generic. Example:

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

目前我有 ToolInfo 结构,因为据我所知,在实例化通用类对象时不可能在 <> 中传递类型.但我还是无法比较.

Currently i have ToolInfo struct, because as far as I know its not possible to get type passed in <> while instantiating generic class object. But I'm still unable to compare it.

推荐答案

意思是运算符不能和右边的变量一起使用?

It means that is operator cannot be used with variables on the right side?

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

Correct. The right side of is must be hard-coded at compile-time.

如果你不需要多态并且你的类型是类类型,你可以使用 === 将实例的 dynamicType 与类类型进行比较.这是在纯 Swift 中在某些内容的右侧获得类型化变量的唯一方法.

If you don't need polymorphism and your types are class types, you can use === to compare the dynamicType of an instance with a class type. That's the only way you're going to get a type-in-a-variable on the right side of something in pure Swift.

这篇关于斯威夫特“是"类型存储在变量中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆