简体   繁体   English

如何在Swift中比较通用对象?

[英]How to compare generic objects in Swift?

consider the following simplified snippet: 考虑以下简化代码段:

class Foo<T: Equatable> {
    var x: T
    init(_ x: T, _ y: T) {
        self.x = x
        if (x == y) {
            // do something
        }
    }
}

I would like this class to work for all kinds of T s that are somehow comparable. 我希望该课程适用于所有可以比较的T Ideally it would compare the identities if T is an object and directly compare everything else that conforms to Equatable . 理想情况下,它将比较T是否为对象的身份,并直接比较符合Equatable其他所有内容。
The code above doesn't work for Array for example. 例如,上面的代码不适用于Array If I change Equatable to AnyObject and == to === then it doesn't work for Int s. 如果将Equatable更改为AnyObject并且将==更改为===则不适用于Int How do I solve this problem? 我该如何解决这个问题? I thought about creating my own protocol but then I couldn't figure out how to implement it for all types that conform to Equatable . 我考虑过要创建自己的协议,但是后来我Equatable来如何对所有符合Equatable类型实现该Equatable

Edit: 编辑:
I didn't know that it would work on the Mac because I am on Linux and when I try to compile 我不知道它是否可以在Mac上运行,因为我在Linux上并且在尝试编译时

Foo<[Int]>([1, 2], [1, 2])

I get the following error: 我收到以下错误:

error: type '[Int]' does not conform to protocol 'Equatable'
Foo<[Int]>([1, 2], [1, 2])
^

A simple solution would be to simply add another initializer for arrays of Equatable elements. 一个简单的解决方案是简单地为Equatable元素数组添加另一个初始化程序。

class Foo<T: Equatable> {
    init(_ x: T, _ y: T) {
        if (x == y) {
            print("Initialization by equal equatable types.")
        }
    }

    init(_ x: [T], _ y: [T]) {
        if (x == y) {
            print("Initialization by equal arrays of equatable types.")
        }
    }
}

let a = Foo<Int>(1, 1)
    /* Initialization by equal equatable types. */
let b = Foo<Int>([1, 2, 3], [1, 2, 3])
    /* Initialization by equal arrays of equatable types. */

Depending on what you intend to do with Foo, it may not be necessary to make it a generic class but rather just have generic initializers: 根据您打算对Foo进行的操作,可能不必使它成为泛型类,而只需要泛型初始化器即可:

class Foo 
{
    init<T:Equatable>(_ x: T, _ y: T) 
    {
        if (x == y) 
        {
            // do something
        }
    }

    init<T:AnyObject>(_ x: T, _ y: T) 
    {
        if (x === y) 
        {
            // do something
        }
    }
}

// in Playground ...

class Bar { }

let C = Foo(3,4)  // no error

let O1 = Bar()
let O2 = Bar()

let D = Foo(O1,O2)  // no error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM