【问题标题】:The correct JSON comparison with Strings (SWIFT 3)JSON 与字符串的正确比较 (SWIFT 3)
【发布时间】:2016-11-14 12:07:51
【问题描述】:
    request( url!, method: .get, parameters: nil)
        .responseJSON { response in

            print(response.result)   // result of response serialization

            if let newJSON = response.result.value {
                let json = JSON(newJSON)
                for (key,subJson):(String, JSON) in json {

                    let age = subJson["age"]
                    let name = subJson["name"]
                    let status = subJson["status"]

  //the code below looks kind of confusing if it gets longer

                    if age == "22"{
                        if status == "highschool "{
                            if name == "Leo"{
                              //do something with the result 

有没有更好的方法来检查 JSON 的结果是否与字符串相同?

【问题讨论】:

    标签: json xcode if-statement swift3


    【解决方案1】:

    这是经典的pyramid of doom。有几种方法可以摆脱它,您需要根据您的上下文选择合适的方法。基本上方法是:

    • 使用提前退货和guard 声明。
    • 将多个if-let 语句合并为一个。
    • 使用for-where

    鉴于以上所有内容,您可以将您的一段代码重写为如下内容:

    request( url!, method: .get, parameters: nil)
        .responseJSON { response in
            print(response.result)   // result of response serialization
    
            guard let newJSON = response.result.value else { return }
    
            let json = JSON(newJSON)
    
            for (key,subJson):(String, JSON) in json {
                let age = subJson["age"]
                let name = subJson["name"]
                let status = subJson["status"]
    
                if age == "22" && status == "highschool" && name == "Leo" {
                    //do something with the result 
                }
            }
        }
    

    【讨论】:

    • Xcode 在 name age status 之前问我插入 let 。当我这样做时,它会给我错误。 条件绑定的初始化器必须具有可选类型
    • @leo0019 似乎 subJson["age"] 不是可选的。那么就没有必要这样做guard dance,只需将它们声明为普通常量即可。编辑了答案。
    【解决方案2】:

    两种选择:

    if age == "22" && status == "high school " && name == "Leo" {
    

    switch (age, status, name) {
        case ("22", "high school ", "Leo"): ...
        ...
        default: ...
    }
    

    【讨论】:

      最近更新 更多