抓住任何错误,特别是在swift中意外发现nil

时间:2016-01-26 05:56:08

标签: swift

我如何捕获任何错误,我指的是任何类型,包括致命错误,异常,任何类型......
在其他语言中我们会使用try,catch,但是当它包装nil值时,do,catch不会成功。但为什么?真的是为什么?

3 个答案:

答案 0 :(得分:7)

如果我需要解包许多可选值,例如在处理Any值集合时,编写多个guard letif let语句并不方便。相反,我正在使用do-try-catch来处理nil。为实现这一目标,我正在使用这个简单的unwrap代码段:

public struct UnwrapError<T> : Error, CustomStringConvertible {
    let optional: T?

    public var description: String {
        return "Found nil while unwrapping \(String(describing: optional))!"
    }
}


func unwrap<T>(_ optional: T?) throws -> T {
    if let real = optional {
        return real
    } else {
        throw UnwrapError(optional: optional)
    }
}

用法:

do {
    isAdsEnabled = try unwrap(dictionary["isAdsEnabled"] as? Bool)
    // Unwrap other values...
} catch _ {
    return nil
}

答案 1 :(得分:5)

不幸的是,这并不存在于swift中。

您可以捕获由以下函数抛出的错误:

do {
   let outcome = try myThrowingFunction()
} catch Error.SomeError {
   //do stuff
} catch {
  // other errors
}

或忽略抛出的错误,然后继续这样:

let outcome = try? myThrowingFunction()

但是无法发现无法预料的崩溃

答案 2 :(得分:1)

使用do-catch语句通过运行代码块来处理错误。如果do子句中的代码抛出错误,则会与catch子句匹配,以确定哪一个可以处理错误。

你用试试?通过将其转换为可选值来处理错误。如果在评估try时抛出错误?表达式,表达式的值为nil。例如,在下面的代码中,x和y具有相同的值和行为:

func someThrowingFunction() throws -> Int {
    // ...
}

let myValue1 = try? someThrowingFunction()

let myValue2: Int?
do {
    myValue2 = try someThrowingFunction()
} catch {
    myValue2 = nil
}

如果someThrowingFunction()抛出错误,则myValue1和myValue2的值为nil。否则,myValue1和myValue2的值是函数返回的值。请注意,myValue1和myValue2是someThrowingFunction()返回的任何类型的可选项。这里函数返回一个整数,因此myValue1和myValue2是可选的整数。

使用试试?当您想以相同的方式处理所有错误时,可以编写简洁的错误处理代码。例如,以下代码使用多种方法来获取数据,或者如果所有方法都失败则返回nil

func fetchData() -> Data? {
    if let data = try? fetchDataFromDisk() { return data }
    if let data = try? fetchDataFromServer() { return data }
 return nil
}

如果你想检查nil值,你也可以这样使用: -

var myValue: Int?


if let checkValue:Int = myValue {
  // run this when checkValue has a value which is not ni
}