简体   繁体   English

swift如何比较泛型

[英]swift how to compare generics

I have a protocol called SomeProtocol 我有一个名为SomeProtocol的协议

I want to create a function that get an object that confirms to this protocol, and add it to an array. 我想创建一个函数,获取一个确认该协议的对象,并将其添加到数组中。

then I have another function that remove an object from this array. 然后我有另一个从该数组中删除对象的函数。

var allObjs = [SomeProtocol]()

func addObj<T: AnyObject where T: SomeProtocol>(obj: T) {
    allObjs.append(obj)
}

func removeObj<T: AnyObject where T: SomeProtocol>(obj: T) {
    for someObj in allObjs {
        if someObj == obj { // compile time error -> Binary operator '==' cannot be applied to operands of type 'SomeProtocol' and 'T'

        }
    }
}  

This code will cause a compile time error "Binary operator '==' cannot be applied to operands of type 'SomeProtocol' and 'T'" 此代码将导致编译时错误“二进制运算符'=='不能应用于'SomeProtocol'和'T'类型的操作数”

not sure how can i fix that, both object where defined as AnyObject who confirm to the SomeProtocol protocol, so what is the problem here? 我不确定如何解决这个问题,这两个对象都定义为确认为SomeProtocol协议的AnyObject,那么这里的问题是什么?

If you want reference equality, then you need to ensure SomeProtocol only applies to classes (since you can't use reference equality on structs, as they're value types): 如果你想要引用相等,那么你需要确保SomeProtocol只适用于类(因为你不能在结构上使用引用相等,因为它们是值类型):

protocol SomeProtocol: class { }

Now, only classes can implement SomeProtocol . 现在,只有类可以实现SomeProtocol

You don't need generics to use reference equality now, just regular run-time polymorphism: 你现在不需要泛型来使用引用相等,只需要常规的运行时多态性:

func removeObj(obj: SomeProtocol) {
    // since any SomeProtocol-conforming object
    // must be a class, you can now use ===
    if let idx = allObjs.indexOf({ $0 === obj}) {
        allObjs.removeAtIndex(idx)
    }
}

泛型函数还必须符合Equatable协议

For comparing two generics, you can declare the generics such that, types, that are capable to be in the place of your generic type, should conform to Comparable protocol. 为了比较两个泛型,您可以声明泛型,使得能够代替泛型类型的类型应符合Comparable协议。

struct Heap<T: Comparable>{
var heap = [T]()
}}

Now we will be able to do:- 现在我们可以做到: -

if heap[parentIndex] < heap[childIndex] {
//Your code
}

How this works? 这是怎么回事?

As we know, conforming to a protocol means implementing all the required methods in that protocol. 我们知道,符合协议意味着在该协议中实现所有必需的方法。 Comparable protocol has got all the comparison methods as required parameters, and any type that is implementing Comparable will be able to do a comparison. 可比协议已将所有比较方法作为必需参数,并且任何实现Comparable的类型都能够进行比较。

Happy coding using Generics. 使用泛型的快乐编码。

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

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