Created
November 12, 2015 17:19
-
-
Save pyrtsa/05baea18e568f72c8e55 to your computer and use it in GitHub Desktop.
"Throwing subscripts" in Swift 2
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
infix operator « { associativity left } | |
infix operator »« { associativity left } | |
postfix operator » {} | |
struct Index { | |
let value: Int | |
} | |
enum Error : ErrorType { | |
case OutOfBounds(index: Int, count: Int) | |
} | |
postfix func » (index: Int) -> Index { | |
return Index(value: index) | |
} | |
func « <T>(array: [T], index: Int) throws -> T { | |
if array.indices ~= index { return array[index] } | |
throw Error.OutOfBounds(index: index, count: array.count) | |
} | |
func « <T>(array: [T], index: Index) throws -> T { | |
if array.indices ~= index.value { return array[index.value] } | |
throw Error.OutOfBounds(index: index.value, count: array.count) | |
} | |
func »« <T>(array: [T], index: Index) throws -> T { | |
if array.indices ~= index.value { return array[index.value] } | |
throw Error.OutOfBounds(index: index.value, count: array.count) | |
} | |
do { | |
let xs = [[0],[10, 20, 30]] | |
print(try xs«0») //=> "[0]" | |
print(try xs«0»«0») //=> "0" | |
print(try xs«1»«2») //=> "30" | |
print(try xs«0») //=> "[0]" | |
print(try xs«3») // throws OutOfBounds(3, 3) | |
print(try xs«0») | |
} catch let e { | |
print(e) //=> "OutOfBounds(3, 3)" | |
} |
Yes it is useful while we wait for language support for throwing subscripts!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is obviously very silly when defined for
Array
s, but who knows maybe it's useful in some domain-specific language for someone some day.A bit of extra effort was needed for nested subscripting because
»«
is considered as an operator of its own byswiftc
.