To prevent potential crashes, whenever I attempt to access a specific element in an array I normally do some safety-checks. I just realised I'm kinda tired of doing that. Is there a way to do it quickly and safely?
var array:[String] = [/*Filled with stuff*/]
func someFunc(someIndex:Int){
//This is unsafe. It will crash if index is negative or larger than count.
let text = array[someIndex]
//This is completely safe, but boring.
let text:String
if someIndex >= 0 && someIndex < array.count{
text = array[someIndex]
}else { return }
//What I want is something like this:
let text = array.hasElement(at: someIndex) ? array[someIndex] : return
//I know, I can't really put a 'return' in a statement like this, but I really want to..
//Optimally, I'd like something like this:
guard let text = array[someIndex] else { return }
//But this is illegal because it's not an conditional binding with an optional type.
}
While writing this I realised I could probably create my own extension of Sequence
or something, to add a function for func hasElement(at:Int)->Bool
. But I'd rather want a way to use guard
since I can't do an inline condition ? true : return
..
Any one-liners are appreciated..