Is it considered bad practice to do this
if self.arrayOfStrings != nil{
textLabel.text = self.arrayOfStrings![0]
}
Not bad practice, and I do sometimes do it; but it is unnecessary and a bit unusual, because this is the situation that conditional bindings are intended to resolve.
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.
"Creating an if let
variable" is not "unnecessary". It is the elegant way to handle this. What you are proposing to do is what is "unnecessary" (and it is wasteful because you are compelling the runtime to access self.arrayOfStrings
twice).
You have two choices, depending on whether everything needs to come to a halt if arrayOfStrings
is nil
.
You can put a guard:
guard let arr = self.arrayOfStrings else {return}
textLabel.text = arr[0]
Or you can use a conditional binding:
if let arr = self.arrayOfStrings {
textLabel.text = arr[0]
}
The difference (aside from the early exit) is the scope of arr
.
So, although to some extent this is a matter of opinion, I would say that the problem here lies in your sense of what is elegant.