简体   繁体   中英

swift how to compare generics

I have a protocol called 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'"

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?

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):

protocol SomeProtocol: class { }

Now, only classes can implement 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.

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.

Happy coding using Generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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