如何在swift中检查两个实例是相同的类/类型 [英] How to check two instances are the same class/type in swift

查看:108
本文介绍了如何在swift中检查两个实例是相同的类/类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用 is

if item is Movie {
    movieCount += 1
} else if item is Song {
    songCount += 1
}

但是如何检查两个实例是否具有相同的类?以下方法不起作用:

but how can I check that two instances have the same class? The following does not work:

if item1 is item2.dynamicType {
    print("Same subclass")
} else {
    print("Different subclass)
}

我可以很容易地添加一个类"函数并在每个子类中更新它以返回一些独特的东西,但这似乎是一个麻烦...

I could easily add a "class" function and update it in each subclass to return something unique, but that seems like a kludge...

推荐答案

我觉得有必要首先引用 Swift Programming Language 文档:

I feel necessary to quote from the Swift Programming Language documentation first of all:

类具有结构所没有的附加功能:

  • 类型转换使您能够在运行时检查和解释类实例的类型.

<小时>

据此,可能对以后的人有所帮助:


According to this, it may be helpful for someone in the future:

func areTheySiblings(class1: AnyObject!, class2: AnyObject!) -> Bool {
    return object_getClassName(class1) == object_getClassName(class2)
}

<小时>

和测试:


and the tests:

let myArray1: Array<AnyObject> = Array()
let myArray2: Array<Int> = Array()
let myDictionary: Dictionary<String, Int> = Dictionary()
let myString: String = String()

let arrayAndArray: Bool = self.areTheySiblings(myArray1, class2: myArray2) // true
let arrayAndString: Bool = self.areTheySiblings(myArray1, class2: myString) // false
let arrayAndDictionary: Bool = self.areTheySiblings(myArray1, class2: myDictionary) // false

<小时>

更新

你也可以重载一个新的操作符来做这样的事情,例如这个:


UPDATE

you also can overload a new operator for doing such a thing, like e.g. this:

infix operator >!<

func >!< (object1: AnyObject!, object2: AnyObject!) -> Bool {
   return (object_getClassName(object1) == object_getClassName(object2))
}

和结果:

println("Array vs Array: \(myArray1 >!< myArray2)") // true
println("Array vs. String: \(myArray1 >!< myString)") // false
println("Array vs. Dictionary: \(myArray1 >!< myDictionary)") // false

更新#2

您也可以将它用于您自己的新 Swift 类,例如那些:

class A { }
class B { }

let a1 = A(), a2 = A(), b = B()

println("a1 vs. a2: \(a1 >!< a2)") // true
println("a1 vs. b: \(a1 >!< b)") // false

这篇关于如何在swift中检查两个实例是相同的类/类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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