Swift處理異常

來源:互聯網
上載者:User

標籤:row   cat   UNC   utf8   erro   成功   let   import   throw   

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)

    }

 

    

    

}

Swift處理異常

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.