-
-
Save hsavit1/3337f80d9fe1396c44ce to your computer and use it in GitHub Desktop.
Protocol vs generic type extensions - overload resolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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