Handling try and throws in Swift 3

后端 未结 1 802
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-23 16:15

Before Swift 3 I was using:

guard let data = Data(contentsOf: url) else {
                print(\"There was an error!)
                return
            }
<         


        
相关标签:
1条回答
  • 2020-12-23 17:10

    The difference here is that Data(contentsOf: url) does not return an Optional anymore, it throws.

    So you can use it in Do-Catch but without guard:

    do {
        let data = try Data(contentsOf: url)
        // do something with data
        // if the call fails, the catch block is executed
    } catch {
        print(error.localizedDescription)
    }
    

    Note that you could still use guard with try? instead of try but then the possible error message is ignored. In this case, you don't need a Do-Catch block:

    guard let data = try? Data(contentsOf: url) else {
        print("There was an error!")
        // return or break
    }
    // do something with data
    
    0 讨论(0)
提交回复
热议问题