加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何检查两个实例是相同的类/类型在swift

发布时间:2020-12-14 06:00:29 所属栏目:百科 来源:网络整理
导读:我知道,我可以检查一个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("Differ
我知道,我可以检查一个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)
}

我可以很容易地添加一个“类”函数,并更新它在每个子类返回一些独特的,但似乎像一个kludge …

我觉得有必要引用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读