呼叫可以抛出,但它没有标记为"尝试"并且没有处理错误

时间:2017-06-22 08:55:43

标签: swift3 try-catch ios10

覆盖func viewDidLoad(){         super.viewDidLoad()

    //get the values from sql/Json
    let url = URL(string: "https://example.com/dropdownmenu/phpGet.php")
    let data = Data(contentsOf: url! as URL)
    var tmpValues = try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
    tmpValues = tmpValues.reversed() as NSArray
    reloadInputViews()

    for candidate in tmpValues {
    if let cdict = candidate as? NSDictionary {

            //fullName is the column name in sql/json

            let names = cdict["fullName"]
            self.values.append(names! as AnyObject)

        }
    }

}

enter image description here

1 个答案:

答案 0 :(得分:12)

let optData = try? Data(contentsOf: url! as URL)
guard let data = optData else {
    return
}

数据(contentsOf:url!as URL)可以抛出异常,您需要尝试调用。 通过使用let optData = try? ...如果抛出异常,您将拥有有效的Data对象或nil