2

I was trying to create a complex Array in the playground with the way below:

import UIKit

let demoData = [
    [
        "name":"Mr Bean",
        "number": "012345678",
        "address": "4 D. Street",
        "dob": "21-9-1970",
        "gender": "male",
        "docs": [
            "alerts":["jt_alert_1.jpg", "jt_alert_2.jpg"],
            "notes":["jt_notes_1.png", "jt_notes_2.jpg", "jt_notes_3.jpg", "jt_notes_4.jpg"],
            "correspondence": [],
            "investigations": [],
            "operationsheets": [],
            "treatmentcharts": []
        ]
    ],
    [
        "name":"Jenny Thomas",
        "number": "012345679",
        "address": "5 D. Street",
        "dob": "22-9-1970",
        "gender": "female",
        "docs": [
            "alerts":[],
            "notes":[],
            "correspondence": [],
            "investigations": [],
            "operationsheets": [],
            "treatmentcharts": []
        ]
    ]
];

let notes: AnyObject? = demoData[0]["docs"]!["notes"]!
let notePics = notes as Array<String>
notePics[0]

The spinning wheel at the bottom right corner keeps spinning for ever. When i created a new swift project, the same code froze everything while XCode was indexing

Does anyone else had the same problem? If yes, any solutions?

Thanks in advance

Astri
  • 575
  • 4
  • 10
  • I'm pretty sure the problem is the same as for [this question](http://stackoverflow.com/q/26550775/148357): the statement is too long – Antonio Oct 24 '14 at 22:12

1 Answers1

0

Your data is very complex making it hard for Swift to figure out what you are doing. Give the compiler a hint as to the structure of demoData:

let demoData:[[String:AnyObject]] = [
   ...

and all will be good.

You might also want to be more explicit about what you expect to find while unpacking your structure:

if let docdict = demoData[0]["docs"] as? [String:AnyObject] {
    if let notePics = docdict["notes"] as? [String] {
        println(notePics[0])
    }
}

The optional binding (if let) combined with conditional casts (as?) provides extra safety to your program. If you were wrong about one of the keys, or if you are wrong about the data type of the value, this will simply never enter the inner block. If you use force unwrapping (!), your program will crash if the key is not in your dictionary. Likewise, if you cast the value (with as) to a type that it is not, your program will crash.

vacawama
  • 150,663
  • 30
  • 266
  • 294