Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Protocol vs generic type extensions - overload resolution
// works for any index type
extension CollectionType {
var mid: Index {
return advance(startIndex,
distance(startIndex,endIndex) / 2
)
}
}
// and specialize for random-access index types
extension CollectionType where Index: RandomAccessIndexType {
var mid: Index {
return startIndex.advancedBy(
startIndex.distanceTo(endIndex) / 2
)
}
}
// string indices are bidirectional
let s = "hello"
let stringRange = s.startIndex..<s.endIndex
// so Swift calls the more general version
stringRange.mid
// but Ints is random-access
let intRange = 0..<10
// so Swift calls the more specialized version
intRange.mid
/// Now the same thing, but with an extension on Range instead of CollectionType
// works for any index type
extension Range {
var mid: T {
return advance(startIndex,
distance(startIndex,endIndex) / 2
)
}
}
// and specialize for random-access index types
extension Range where T: RandomAccessIndexType {
var mid: T {
return startIndex.advancedBy(
startIndex.distanceTo(endIndex) / 2
)
}
}
let s = "hello"
let stringRange = s.startIndex..<s.endIndex
// singe String.Index is bidirectional, no ambiguity
stringRange.mid
// but Ints being random-access
let intRange = 0..<10
// Swift complains error: ambiguous use of 'mid'
intRange.mid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.