Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
arr&[-1] array accessor that checks if index is out of range, and returns an optional....
let arr = [1,2,3,4]
func & <T>(lhs:Array<T>,rhs:[Int]) -> T?{
guard let index = rhs.first else{
print("no index!")
return nil
}
if index < 0{
print("negative index")
return nil
}
if index >= lhs.count{
print("index \(index) out of range 0-\(lhs.count-1)")
return nil
}
return lhs[index]
}
let x = arr&[-1] //nil
let y = arr&[10] //nil
let z = arr&[ 0] //1
func randomIndex(index:Int)->Int?{
guard let res = arr&[index] else {
print("something went terribly wrong...")
return nil
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment