Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created November 12, 2015 17:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)"
}
@pyrtsa
Copy link
Author

pyrtsa commented Nov 12, 2015

This is obviously very silly when defined for Arrays, 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 by swiftc.

@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