Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Forked from airspeedswift/protocolextension.swift
Created October 31, 2015 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsavit1/3337f80d9fe1396c44ce to your computer and use it in GitHub Desktop.
Save hsavit1/3337f80d9fe1396c44ce 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