Swift处理异常

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

let jsonStrl = "{\"name\": \"Lao Wang\"]"

let data = jsonStrl.data(using: .utf8)

//反序列化  throw抛出异常

//方法一:推荐 try? 如果解析成功,就有值,否则为nil

//        let dict = try? JSONSerialization.jsonObject(with: data!, options:[])

//方法二: 不推荐 try! 如果解析成功,就有值,否则崩溃,有风险

//        let dict = try! JSONSerialization.jsonObject(with: data!, options:[])

//方法三: 处理异常,能够接受到错误,并且输出错误

do {

let dict = try JSONSerialization.jsonObject(with: data!, options:[])

print(dict)

} catch {

print(error)

}

//        print(dict)

}

}

上一篇:java字符串占位符%s


下一篇:论文参考文献引用cff文件