swift - How to prevent a 'Array index out of range' error? -
is there way, similar using if let
and/or optionals, test whether index empty buffer in swift?
define own:
extension array { func ref (i:int) -> t? { return 0 <= && < count ? self[i] : nil } }
the ref()
function returns optional, can nil
, , can use if let
syntax access returned value ref()
when exists. use such:
var mya = [10,20,30] if let val = mya.ref(index) { // use 'val' if index < 3 } else { // if index high }
Comments
Post a Comment