Swift 3 – Iterating through Dictionaries
These are formatted so you can copy the code straight into your Swift Playground files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
//create a Swift 3 dictionary with values // just to show we can, lets change the value types, // so the dictionary type is [String : AnyObject] var someDict = ["Current Zip Code" : 34050, "Previous Zip Code" : 43256, "Next Zip" : "the moon"] var someString:String = "" // will use later... for (theKey, theValue) in someDict { //iterate through the dictionary until we find the previous zip code if (theKey == "Previous Zip Code") { //check what the value type is before doing anything with it if let possibleNumber:Int = theValue as? Int { //possibleNumber was successfully created equaling theValue print (possibleNumber) } } // another approach... else if (theKey == "Next Zip") { //check if its a string... if (theValue is String) { //it's safe to force someString to equal theValue since // we know it's definitely a string... someString = theValue as! String } } } |
If you’re looking for places to learn after these Swift Playground examples, check out CartoonSmart.com or SpriteKitLessons.com