如何在不同的条款中快速使用JSOn响应

时间:2015-04-30 08:27:33

标签: ios json swift

我使用swifty.JSON来解析JSON,我得到了预期的输出

var outPut = JSON(data: data!)

但我想将此outPut variable声明为global,以便将其作为函数的返回值返回。因为我想在其他类中使用此JSON响应。怎么弄这个?

2 个答案:

答案 0 :(得分:0)

像这样获取$.questionField.addEventListener("change", function(e){ var words = $.questionField.value.split(" ").length; var characters = $.questionField.value.replace(/[^A-Z]/gi, "").length; console.log("characters " + characters); if (words > 5 && characters > 20) { if (OS_IOS) { $.submitIconSubmitPage.touchEnabled = true; $.submitIconSubmitPage.color = "green"; } } else if (words <= 5 || characters <= 20){ if (words <=5) { $.wordCounter.color = "red"; $.wordCounter.text = 5 - words; } else { $.wordCounter.color = "green"; } if (characters <=20) { $.characterCounter.color = "red"; $.characterCounter.text = 20 - characters; } else { $.characterCounter.color = "green"; } if (OS_IOS) { $.submitIconSubmitPage.touchEnabled = false; $.submitIconSubmitPage.color = "red"; } } }); AppDelegate

object

现在将let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate var jsonData添加到object。对此对象的AppDelegate数据如下:

Set

答案 1 :(得分:0)

@prince是对的,但是如果你想要一个函数,你可以试试这样的东西:

// I'm declaring the return type as `JSON` since I think it's what SwiftyJSON creates. 
// I also make it an Optional since it can be nil.
func getJSONFromRequest(data: NSDictionary?) -> JSON? { 
    if let myData = data, let result = JSON(data: myData) {
        return result
    }
    return nil
}

let myJSON = getJSONFromRequest(data: myDataFromNetwork)

这只是一个例子,你应该根据你的具体情况进行调整。