Reputation:
With this code I enable a button if any form value is not nil
:
myButton.isEnabled = !myForm.values.contains(where: { $0 == nil })
Is there any way to add multiple checks? I want to enable my button:
(that is, the value should NOT be nil and should NOT be outside the range 0.0 - 2.0)
Can I still use contains(where:) to do it?
MyForm is a dictionary like this one:
["oct": nil,
"jan": Optional(3666.0),
"nov": nil,
"apr": nil,
"sep": nil,
"feb": nil,
"jul": nil,
"mar": nil,
"dec": nil,
"may": nil,
"jun": nil,
"aug": nil]
(strange enough, due to the behavior of a 3rd party library, it accepts nil
values)
Upvotes: 0
Views: 135
Reputation: 285180
Yes, you can. If you want to enable the button if there is at least one Double
value in range 0.0..<2.0
you don't need to call values
. You can call contains
on the dictionary directly. The where
keyword is syntactic sugar and can be omitted when using trailing closure syntax.
The code uses the pattern matching operator to check the range.
myButton.isEnabled = myForm.contains { (_, value) in
guard let value = value as? Double else { return false }
return 0.0..<2.0 ~= value
}
If you want to enable the button if all values are Double
in the given range you have to check inverted
myButton.isEnabled = !myForm.contains { (_, value) in
guard let value = value as? Double else { return true }
return !(0.0..<2.0 ~= value)
}
Upvotes: 1
Reputation: 2829
You can do it just by filtering all values like this:
myButton.isEnabled = !myForm.values.filter {
if let value = $0 { return value.field > 0.0 && value.field < 2.0 }
return false
}.count > 0
contains
function is not appropriate solution in your case, because it should be used when you need to check if array contain some specific element. But in your case you need to check if values is in specific range.
It is possible to use contains
function but it is not correct way
Upvotes: 1