Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created November 12, 2015 17:19
Show Gist options
  • Save pyrtsa/05baea18e568f72c8e55 to your computer and use it in GitHub Desktop.
Save pyrtsa/05baea18e568f72c8e55 to your computer and use it in GitHub Desktop.
"Throwing subscripts" in Swift 2
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)"
}
@nbransby
Copy link

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