将 NSURLConnection 与 Swift 一起使用

Using NSURLConnection With Swift

我正在使用以下代码从 API:

中获取数据
typealias JSONdic = [String: AnyObject]

if let json = json as? JSONdic, history = json["history"] as? JSONdic, hour = history["hour"] as? String {
println(hour)
}

但是,Xcode 告诉我 "json" 不是可识别的标识符。我相信这可以用 NSURLConnection 解决,但我不知道如何使用它。任何人都可以提供使用此协议的任何示例吗?

您通过将变量设置为自身来声明变量,这没有任何意义。为了在赋值的右侧使用变量,它需要已经声明。因此,让我们在转换语句之外给 json 一个值,它工作正常。

typealias JSONdic = [String: AnyObject]

let json: AnyObject = ["greeting": "Hello"]
if let json = json as? JSONdic, history = json["history"] as? JSONdic, hour = history["hour"] as? String {
    println(hour)
}