Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force unwrapping after checking if nil?

Tags:

swift

Is it considered bad practice to do this

I am checking if the array is nil, then force unwrapping to retrieve an element from the array. I am doing this to avoid creating an unnecessary if let variable.

if self.arrayOfStrings != nil{
    textLabel.text = self.arrayOfStrings![0]
}
like image 511
Brian Green Avatar asked Jan 27 '23 16:01

Brian Green


1 Answers

Yes, it is bad practice. Perhaps not in this case specifically but it is possible that some other thread could update the property and make it nil between this thread checking for nil and then force-unwrapping.

Just do:

if let arrayOfStrings = self.arrayOfStrings {
    textLabel.text = arrayOfStrings[0]
}

There is no unnecessary variable here since you actually use the variable inside the if let.

Of course in this very specific case of trying to get the first value of an optional array, you can simply do:

textLabel.text = self.arrayOfStrings?.first

If you actually wanted something other than index 0, you should check the index:

if let arrayOfStrings = self.arrayOfStrings, someIndex < arrayOfStrings.count {
    textLabel.text = arrayOfStrings[someIndex]
}

In none of these cases is the "extra" variable a waste of effort or memory. It is being used in a read-only capacity as a constant and Swift is smart enough not to create a complete copy of the array in the process.

like image 188
rmaddy Avatar answered Feb 09 '23 04:02

rmaddy