Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active May 25, 2019 07:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save airspeedswift/a04cb219d30885cd02ab to your computer and use it in GitHub Desktop.
Save airspeedswift/a04cb219d30885cd02ab to your computer and use it in GitHub Desktop.
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