Swift idiomatic error checking

前端 未结 2 920
别跟我提以往
别跟我提以往 2020-12-10 00:05

Let\'s say that you have a function like this:

func getSomething(error: NSErrorPointer) -> Something

and you typically use it this way:<

2条回答
  •  攒了一身酷
    2020-12-10 00:25

    if a function returns an optional value i.e

    func someFunc(someVar: String) -> NSData? {
      // some code
    }
    

    (the optional means that it can return a nil) then error checking is pretty simple

    if let data = someFunc("someString") {
      // this means there was NO error as the function didn't return a nil
    }
    else {
      // This means there was an error
    }
    

    This video is a pretty good reference for error checking and handling in swift https://youtu.be/m8szaLqHVDs

提交回复
热议问题