我知道,我可以检查一个var在Swift的类型是
if item is Movie { movieCount += 1 } else if item is Song { songCount += 1 }
但是如何检查两个实例具有相同的类?以下不工作:
if item1 is item2.dynamicType { print("Same subclass") } else { print("Different subclass) }
我觉得有必要引用Swift编程语言文档:
Classes have additional capabilities that structures do not:
- Type casting enables you to check and interpret the type of a class instance at runtime.
根据这一点,它可能对未来的人有所帮助:
func areTheySiblings(class1: AnyObject!,class2: AnyObject!) -> Bool { return object_getClassName(class1) == object_getClassName(class2) }
和测试:
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
更新
你也可以重载一个新的操作符来做这样的事情,例如。这个:
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