ios-Swift处理异常的三种方式
程序员文章站
2022-04-23 11:17:56
1、我们手动的去捕捉异常
let jsonStr="lll"
let jsonData=jsonSt...
1、我们手动的去捕捉异常
let jsonStr="lll" let jsonData=jsonStr.data(using: String.Encoding.utf8) //在Swift中options是存放在数组中,如果我们不想写,直接传入一个空数组就可以 do { let result = try JSONSerialization.jsonObject(with: jsonData!, options: [JSONSerialization.ReadingOptions.mutableContainers,JSONSerialization.ReadingOptions.mutableLeaves]) print(result) } catch { print(error) }2、try?尝试try,系统帮我们处理异常,如果发生了异常则会返回nil,如果没有异常就返回相应的对象
let result = try? JSONSerialization.jsonObject(with: jsonData!, options: [JSONSerialization.ReadingOptions.mutableContainers,JSONSerialization.ReadingOptions.mutableLeaves]) print(result)3、try! 是强行try,意思就是直接的说不会有异常,如果出现异常则程序会崩溃
let result = try! JSONSerialization.jsonObject(with: jsonData!, options: [JSONSerialization.ReadingOptions.mutableContainers,JSONSerialization.ReadingOptions.mutableLeaves]) print(result)