Skip to content

Instantly share code, notes, and snippets.

@Nadohs
Created October 25, 2015 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nadohs/304b0da0548752dd4230 to your computer and use it in GitHub Desktop.
Save Nadohs/304b0da0548752dd4230 to your computer and use it in GitHub Desktop.
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