0

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?

1
  • Perhaps you should consider using a struct to encapsulate your data - should make it easier to use than dictionaries of dictionaries. What are you trying to achieve? Commented Jun 17, 2015 at 10:42

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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") } 

2 Comments

Explicit if let -binding of optionals results in safer code. Force unwrapping is more prone to lead to runtime crashes. OP has given us one example of dictionary when we don't know how it might be constructed later on
@TheTom Completely agree about optional bindings. But if OP example might change later then it should change in right direction and thats imo is by reconstructing whole its struct and not using dictionaries at all. Ive just answered what OP was looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.