NSXMLDocument snippet doesn't work

I thought I’d use the example XML Document code near the end of chapter 28 as the basis for the XML challenge. It doesn’t compile. Even if I use it as-is, with the xmlString sample data from the book, XCode complains about trying to create the people array as [NSXMLNodes]

Is this an error in the sample code or is something missing from the snippet that sets this up to work? I realize it is just an illustration and, since it isn’t bold, isn’t meant to be typed in and run but it seems like it is a good starting point for the challenge and I don’t notice anything obviously missing from it.

Thanks for pointing this out. The fix is to change the “as” casts to “as!”. Like this:

var error: NSError?
if let doc = NSXMLDocument(XMLString: xmlString, options: 0, error: &error) {
    if let people = doc.nodesForXPath("//person", error: &error) as! [NSXMLNode]? {
        for person in people {
            let firstNameNodes = person.nodesForXPath("first", error: &error) as! [NSXMLNode]
            if let firstNameNode = firstNameNodes.first {
                println(firstNameNode.stringValue!)
            }
        }
    }
}

This was the result of a later change in Swift – looks like we didn’t catch this one. The change was that as-casts that could fail must have the ! to more clearly indicate that they can fail and trap.