Chilly Chilly - 2 months ago 14
Swift Question

Multiple value checking with swifts guard statement?

Most of my searching here on SO is proving futile. My guard statement works as far as checking each value and correcting it if one is nil. However if two of the values are nil, then I crash unexpectedly finding nil while unwrapping an optional. How does one go about checking that multiple values are not nil using swifts guard statement?

func protectInput() {

guard Double(myAmount.text!) != nil else {
myAmount.text = "0.00"
return
}

guard Double(myRate.text!) != nil else {
myRate.text = "0.00"
return
}

guard Double(myFee.text!) != nil else {
myFee.text = "0.00"
return
}
}


Maybe I am completely on the wrong track, any help with an example would be appreciated. I have read all I can take in. I do not need to compare two values or have some complex comparison.

Answer

Guard statements aren't the right thing to use here. If any of them fail, then you will return from the function and your later statements won't get executed. So if myAmount doesn't have a valid value in it, you'll never correct myRate and myFee.

if Double(myAmount.text ?? "") == nil {
    myAmount.text = "0.00"
} 

This pattern would suit you better:

  • the text value isn't force unwrapped any more, which will prevent one potential crash - ?? is the nil coalescing operator which will use either the text value or, in this case, an empty string
  • there is no return so the function will check all of the values.
Comments