比较Swift中的AnyObjects,而不将它们转换为特定类型 [英] Compare AnyObjects in Swift without casting them to a specific type

查看:227
本文介绍了比较Swift中的AnyObjects,而不将它们转换为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Equatable协议中定义的==运算符比较AnyObject类型的两个对象,导致Swift中的编译错误。有没有人找到一种方法来比较这些对象,而不知道可用于向下转换的对象的真实类型?

An attempt to compare two objects of AnyObject type using '==' operator defined in Equatable protocol result in a compile error in Swift. Did anyone find a way to compare such objects, without knowing the real type of objects that can be used for downcasting?

这个问题的背景是我有一个字典字典< String,AnyObject>其中值应该通过下标提供,那么在某些时候,我需要比较字典中的值,以确保它们是唯一的。

The background for this question is that I have a dictionary Dictionary<String, AnyObject> where values are supposed to be provided though a subscript, then at some point I need to compare the values in the dictionary to make sure that they are unique.

EDIT
以下是演示此问题的代码段。

EDIT Here is a snippet demonstrating the issue.

@objc(FooObject)
public class FooObject: NSManagedObject {

    @NSManaged public var properties: Dictionary<String, AnyObject>

    public subscript(property: String) -> AnyObject? {
        get {
            return properties[property]
        }
        set(newValue) {

            for propertyValue in properties.values {
                if propertyValue == newValue { // This line is not compiling: Cannot invoke '==' with AnyObject
                    println("Values in are expected to be unique!")
                    // Throw an exception here ...
                }
            }

            properties[property] = newValue
        }
    }
}

注意,类似< T:Equatable>在类定义中声明并用作字典的值类型不会解决问题,因为它不能与NSManagedObject子类一起使用。

Note that generic like <T:Equatable> declared in the class definition and used as a value type of the dictionary won't solve the issue as it cannot be used in conjunction with NSManagedObject subclass.

推荐答案

使用===运算符,从Swift文档:

Use the === operator, from the Swift documentation:

Swift还提供了两个身份操作符(===和!==)您可以使用测试两个对象引用是否都引用同一个对象实例。

Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.

这篇关于比较Swift中的AnyObjects,而不将它们转换为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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