无法将json结果转换为struct

时间:2014-11-03 12:46:20

标签: ios json swift struct

我有一个返回类似的API:

{
elements:[{
    name = "user1",
    details =     {
        phone = "0033612345678"
    }
},
{
    name = "user2",
    details =     {
        phone = "0033612346612"
    }
},
{
    name = "test3"
}]
}

每个元素中都没有详细信息键

我已经定义了一个ElementModel.swift文件,我想为elements数组的每个元素创建一个ElementModel实例。

import Foundation

struct ElementModel {
    var name:String
    var phone:String
}

为了获取姓名和电话价值,我创建了以下函数,在正确执行请求时使用(使用delagation)

func getRequestSucceed(results: NSDictionary) {
    println("getRequestSucceed")

    // Loop through list of elements
    let elementsArray = results["elements"] as NSArray
    var elementsTmpArray:[ElementModel] = []

    // Convert each result into Element object
    for var i=0;i<elementsArray.count;i++
    {
        // Get NSDictionary from each element
        let element = elementArray[i] as NSDictionary

        // Create Element object with parameters from dictionary
        var name = element["name"] as String
        var phone:String = ""

        // If details key exists, get phone attribute
        if let details = element["details"] as? NSDictionary {
            println(details["phone"])    // Phone number is correctly displayed
            phone = details["phone"] as String  // Simulator crash occurs the first time
        } else {
            println("Not defined")
        }

        // Create element model with name and phone
        var t = ElementModel(name: name, phone: phone)
        elementsTmpArray.append(t)
    }

    // Update table view
    dispatch_async(dispatch_get_main_queue(), {
        self.elements = elementsTmpArray
        self.elementsTableView!.reloadData()
    })
}

这种方法不起作用,似乎无法以这种方式检索细节[&#34; phone&#34;]。我对swift很新,不熟悉Optional。只是想知道Optional是否参与了这个问题 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

 details["phone"]

如果details是字典,则上述下标表达式的类型是可选的(如果没有与下标对应的元素,则字典返回nil),因此不能将其转换为字符串。您需要在强制转换前将结果展开到String