Heinevolder
Heinevolder

Reputation: 338

How to check bool inside of dictionary

I have the following piece of code:

struct Dare {
  var theDare: [[String: AnyObject]] = [
    ["dare": "Dare1",
     "darePerson": true],
    ["dare": "Dare2",
     "darePerson": false],
    ["dare": "Dare3",
     "darePerson": false],
    ["dare": "Dare4",
     "darePerson": true],
    ["dare": "Dare5",
     "darePerson": false]
]

func randomDare() -> Dictionary<String, AnyObject> {
    return theDare[Int(arc4random_uniform(UInt32(theDare.count)))]
}

}

How can i check a random dare if darePerson == true?

Upvotes: 0

Views: 248

Answers (2)

The Tom
The Tom

Reputation: 2810

From your randomDare function you will have a [String: AnyObject] dictionary.

var dareDic: Dictionary<String, AnyObject> = randomDare()

You can then cast the value as a Bool like this (Using swift 1.2 if let where syntax):

if let darePerson = dareDic["darePerson"] as? Bool where darePerson == true {
   // Do something when true
}

This technique avoids any force unwraps and failed unwrapped optionnals due to a bad dictionary

Upvotes: 2

Zell B.
Zell B.

Reputation: 10286

Your check should be done by using dictionary subscript method with String parameter because your dictionary keys are Strings. Also since your sure that darePersons exits in your dictionary and its value is Bool you can force unwrap both of them

if dare.randomDare()["darePerson"]! as! Bool{
  println("dare person is true")
}

Upvotes: 1

Related Questions