如何在Swift中为特定类型的数组进行扩展

Jie*_* Hu 5 swift

比方说我有:

struct S {
    var num = 0
}
Run Code Online (Sandbox Code Playgroud)

我想实现一个函数allEqual()作为扩展Array<S>,所以我可以做的事情

var s1 = S()
var s2 = S()
var s3 = S()
var equality = [s1,s2,s3].allEqual()
Run Code Online (Sandbox Code Playgroud)

小智 5

比如说具体的类型是S

extension CollectionType where Generator.Element == S {
}
Run Code Online (Sandbox Code Playgroud)

集合类型协议

  • **更新:使用 Swift 3.1** `extension Array where Element == Int` cf. http://stackoverflow.com/a/34672403/1354835 (2认同)