Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between == and : in swift extension where condition

I have a question in swift extension:

protocol Racer {
    var speed: Double { get }
}
extension Sequence where Iterator.Element == Racer {
    func fastest() -> Iterator.Element? {
        return self.max(by: { (a: Iterator.Element, b: Iterator.Element) -> Bool in
            return a.speed < b.speed
        })
    }
}

extension Sequence where Iterator.Element: Racer {
    func bla() -> Void {

    }
}

I am wondering what's the difference between them. In fact, an array of type [Racer] doesn't have bla() function.


Edit 1: There's still a question, assuming we have a struct conform to Racer

struct Human: Racer {
    var speed: Double
}

If we have an Array<Racer>:

let me = Human(speed: 99999)
let you = Human(speed: 99998)
let arr: [Racer] = [me, you]
// Threre's no problem, we can do this
arr.fastest()

// but 
let arr2: [Human] = [me, you]
// this Array won't have the `fastest` function
arr2.fastest() ------> Error!

So, I have to extension both == and : at the same time for the same function?

like image 501
Klein Mioke Avatar asked Sep 17 '25 14:09

Klein Mioke


1 Answers

When using : you are writing an extension for a type that conforms to a particular protocol or inherits a specified class.

When using = you are writing an extension for a specific type, in your case Racer.

You can read more in the docs here.

Edit:

One difference is that when you are using = the type must match, this means that the element type for the array must be Racer. This is why Array[Human] doesn't get the extension method, because the type isn't Racer is actually Human.

You don't need 2 methods, you can change the first one to use : instead of =. Conforming to Racer protocol is enough, it doesn't need to be of Racer type.

like image 178
Radu Diță Avatar answered Sep 20 '25 08:09

Radu Diță