Created
October 25, 2015 00:19
-
-
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....
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
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