Created
January 23, 2017 13:55
-
-
Save dimohamdy/d1211427117748df4e663a6c1801c0c3 to your computer and use it in GitHub Desktop.
handle IndexOutOfBoundsException using try catch Swift 3
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
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