斯威夫特连续投掷

时间:2018-03-23 12:53:10

标签: ios swift error-handling

我有一个抛出错误的swift函数,这个函数由另一个函数调用,由我的viewcontroller调用。 有没有办法将错误从函数1抛出到函数2,并在我的viewcontroller上捕获它而不必在函数2上捕获它? 一些代码来说明:

func function1(fail : int) throws -> Int {
    if fail < 5 {
        throw MyErrors.lessThenFiveError
    }
}

func function2(myNum : int) throws -> Int {
    do {
         let x = try function1(myNum * 2)
    } catch MyErrors.lessThenFiveError { //would like to avoid this
        throw MyErrors.lessThenFiveError
    }
}

//now my viewdidload code
override func viewDidLoad() {
    super.viewDidLoad()

    do {
        let x = try function2(someNumber)
    } catch MyErrors.lessThenFiveError {
        MessageTheUserWithTheError
    }
}

基本上我想避开function2上的CATCH,只是将错误从function1“传播”到viewDidLoad

1 个答案:

答案 0 :(得分:0)

是。您可以在第二个函数中省略do-catch块:

func function1(fail : int) throws -> Int
{
    if fail < 5 {
        throw MyErrors.lessThenFiveError
    }
}

func function2(myNum : int) throws -> Int
{
    try function1(myNum * 2)
}

override func viewDidLoad() 
{
    super.viewDidLoad()
    do {
        let x = try function2(someNumber)

        // Do stuff with x
    } catch MyErrors.lessThenFiveError{
        MessageTheUserWithTheError
    }
}

function1抛出的错误会传播回viewDidLoad()方法。