try try? try! 也是好晕
如这样的情况 报错提示 需要加上 try, try是swift 2.0 的产物
-
1 加上 try?
let jsonStr = "{\"name\": \"xiaoMing\"}"
let data = jsonStr.data(using: .utf8)
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
print(json)
输出
此时输出的为 可选项
Optional({ name = xiaoMing; })
-
2 加上 try!
let jsonStr = "{\"name\": \"xiaoMing\"}"
let data = jsonStr.data(using: .utf8)
let json = try! JSONSerialization.jsonObject(with: data!, options: [])
print(json)
输出
此时输出的是必选项 若是数据格式错误 则直接崩掉
{
name = xiaoMing;
}
-
3 加上 try
let jsonStr = "{\"name\": \"xiaoMing\"}"
let data = jsonStr.data(using: .utf8)
let json = try! JSONSerialization.jsonObject(with: data!, options: [])
print(json)
此时若是无异常则正常执行,若是有错误则进入 catch 输出错误
try? 若执行正确 则输出相应可选项值,若失败则输出nil
try! 若执行正确 则输出相应必选项值,若失败则崩溃
try 写法比较复杂,可以获取到错误原因