Más contenido relacionado
La actualidad más candente (20)
Similar a プロトコル拡張の話? #WWDC21cafe (20)
Más de Tomohiro Kumagai (20)
プロトコル拡張の話? #WWDC21cafe
- 7. こんなプロトコルがあったとき
protocol CollectionType : SequenceType {
typealias Generator : GeneratorType
typealias Index : ForwardIndexType
subscript(index:Index)
-> Generator.Element { get }
var startIndex:Index { get }
var endIndex:Index { get }
}
protocol GeneratorType {
typealias Element
}
- 10. let array = [Int]()
let dictionary = [String:Int]()
array.count
dictionary.count
既定の実装を追加
全てのコレクション型で使える
- 12. let intArray = [Int]()
let strArray = [String]()
intArray.sum
strArray.sum
条件を限定して実装を追加
条件に合致した型だけで使える
- 14. extension CollectionType where
Index : Streamable,
Generator.Element : IntegerType {
func printIndexOf<S:OutputStreamType>
(element:Generator.Element,
inout to stream:S) {
self.indexOf(element)?.writeTo(&stream)
}
}
複数の条件で限定
- 15. extension CollectionType where
Generator.Element : IntegerType,
Index.Distance == Generator.Element {
var average:Generator.Element {
return self.reduce(0) { $0 + $1 } / self.count
}
var count:Index.Distance {
return distance(
self.startIndex, self.endIndex)
}
}
型が同じという前提
- 19. extension CollectionType {
var isEmpty:Bool {
return self.startIndex == self.endIndex
}
}
struct MyCollection : CollectionType {
var isEmpty:Bool {
return reduce(true) { $0 && $1.isEmpty }
}
}
既定の実装は上書き可能