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]
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With