Skip to content

Instantly share code, notes, and snippets.

@dimohamdy
Created January 23, 2017 13:55
Show Gist options
  • Save dimohamdy/d1211427117748df4e663a6c1801c0c3 to your computer and use it in GitHub Desktop.
Save dimohamdy/d1211427117748df4e663a6c1801c0c3 to your computer and use it in GitHub Desktop.
handle IndexOutOfBoundsException using try catch Swift 3
enum ArrayError: Error {
case OutOfBounds(min: Int, max: Int)
}
extension Array {
mutating func set(index:Int, value: Element) throws {
guard self.indices.contains(index) else {
throw ArrayError.OutOfBounds(min: 0, max: (self.count - 1))
}
self[index] = value
}
mutating func get(index:Int) throws -> Any {
guard self.indices.contains(index) else {
throw ArrayError.OutOfBounds(min: 0, max: (self.count - 1))
}
return self[index]
}
}
var myArray : [Float] = [1,2]
do {
try myArray.set(index: 1, value: Float(5))
} catch ArrayError.OutOfBounds(let min, let max) {
print("out of bounds : \(min) => \(max)")
}
// throw exception
do {
try myArray.get(index: 9)
} catch ArrayError.OutOfBounds(let min, let max) {
print("out of bounds : \(min) => \(max)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment