美文网首页
try try? try!

try try? try!

作者: Theshy | 来源:发表于2016-10-29 18:32 被阅读26次

try try? try! 也是好晕

如这样的情况 报错提示 需要加上 try, try是swift 2.0 的产物

like it
  • 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      写法比较复杂,可以获取到错误原因

相关文章

  • try try? try!

    try try? try! 也是好晕 如这样的情况 报错提示 需要加上 try, try是swift 2...

  • try  try  try

    2017年1月9日练了一节艾扬格小班课程,力量和精准练习,让我从胳膊酸到腿,身体累,但心情却很放松,夜里也深沉的睡...

  • try、try?、try!

    try: try与do-catch语句一起使用,并对错误进行详细处理。 try? try?用在错误无关紧要的时候,...

  • try try! try? And Realm

    使用Realm的时候需要取一个Realm的实例,官方示例如下: // Get the default Realm ...

  • Get up and try try try

    迷迷糊糊的状态已经有两个月了 没有方向的乱转着 这是一个低谷和瓶颈 让我不知道怎么继续走下去 每天有家的陪伴 心却...

  • 1-3碎碎念

    ①"try to do" vs "try doing" Try andis often used instead ...

  • try try? try! (转自stackoverflow)

    http://stackoverflow.com/questions/32390611/try-try-try-w...

  • try and try hard

    If you're going to try, go all the way. Otherwise, don't ...

  • Try and Try Hard

    If you're going to try, go all the way. Otherwise, don't ...

  • Try or not try, this is a questi

    我有时候做事情,发现做了反倒一团糟,甚至把以前的成果都抹杀了,甚至连朋友都不能理解而远离你。 这个时候,我就想,是...

网友评论

      本文标题:try try? try!

      本文链接:https://www.haomeiwen.com/subject/xosyuttx.html