user1094081
user1094081

Reputation:

Test for nil values presence in Dictionary

I have the following Dictionary:

["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]

I want to enable a button only when any value of any key is not nil. Is there any functional "magics" to do it without a traditional loop?

Upvotes: 0

Views: 111

Answers (4)

vadian
vadian

Reputation: 285082

I recommend to conform to the standard dictionary definition that a nil value indicates no key and declare the dictionary non-optional ([String:Double]).

In this case the button will be enabled if all 12 keys are present. This is more efficient than filter or contains

button.isEnabled = dict.count == 12

Upvotes: 0

RajeshKumar R
RajeshKumar R

Reputation: 15758

You can use filter to check if any value is nil in a dictionary.

button.isEnabled = dict.filter { $1 == nil }.isEmpty

Upvotes: 1

Martin R
Martin R

Reputation: 539795

Use contains(where:) on the dictionary values:

// Enable button if at least one value is not nil:
button.isEnabled = dict.values.contains(where: { $0 != nil })

Or

// Enable button if no value is nil:
button.isEnabled = !dict.values.contains(where: { $0 == nil })

Upvotes: 3

user8893378
user8893378

Reputation:

You've already been provided with similar solutions, but here you go:

dict.filter({$0.value == nil}).count != 0

Upvotes: 1

Related Questions