Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a extension for array of specific type in Swift

Tags:

swift

for say I have:

struct S {
    var num = 0
}

I wanna implement a function allEqual() as extension for Array<S>, so I could do thing like

var s1 = S()
var s2 = S()
var s3 = S()
var equality = [s1,s2,s3].allEqual()
like image 767
Jieyi Hu Avatar asked Aug 05 '15 20:08

Jieyi Hu


2 Answers

for say the specific type is S

extension CollectionType where Generator.Element == S {
}

CollectionType Protocol

like image 93
sharpBaga Avatar answered Nov 04 '22 22:11

sharpBaga


In the latest Swift 3.1. You can do same-type constraints on the concrete type extension. So in your case, you can do:

extension Array where Element == S {
    func allEqual() -> Bool {
        ...
    }
}
like image 23
J.Wang Avatar answered Nov 04 '22 22:11

J.Wang