T-Rex
T-Rex

Reputation: 1550

Swift elegant condition for dictionary with boolean values

Sorry, by the time I finished writing the question, I noticed it didn't work because of a stupid syntax mistake... I'm posting this anyway because

Trying to make things a little more elegant... I have an optional dictionary of [String:Bool] and a String key. Now, in one condition I want to ask:

The solution:

var topics:[String:Bool]?

let topicName="Pictures"

if self.topics?[topicName] ?? false {
    //do stuff
}

Upvotes: 1

Views: 7295

Answers (3)

mattliu
mattliu

Reputation: 820

A more verbose idiom that I sometimes prefer (depending on the situation):

var topics:[String:Bool]?

let topicName="Pictures"

if let topicIsSelected = self.topics?[topicName] where topicIsSelected {
    //do stuff
}

Update: The Swift 3 version of this (the above doesn't compile in Swift 3) doesn't read as nicely:

var topics:[String:Bool]?

let topicName="Pictures"

if let topicIsSelected = self.topics?[topicName], topicIsSelected {
    //do stuff
}

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59506

Why are you using Boolean instead of Bool?

This should work

var topics:[String:Bool]?

if topics?["Pictures"] == true {
    // you have a dictionary
    // AND the requested key does exist
    // AND its value is true
}

Upvotes: 0

Tali
Tali

Reputation: 869

Why use a dictionary when you only want to store one bit of information?

Wouldn't it be much easier to just store a set of strings? Add all strings for which you would store true in your dictionary. Then just test if your string is contained in the set.

Also there is no need for the optional. Just use an empty set instead of nil.

var topics: Set<String>
...
if topics.contains("Pictures") { ... }

Upvotes: 0

Related Questions