如何使 Swift 2 函数抛出异常

How to make a Swift 2 function throw exception

这是我当前的代码

class HelloWorld {
    func foobar() {
        // ...
    }
}

如何使此函数在调用时抛出异常并发生意外情况?

首先,您可以创建一个包含错误的枚举,并实现 ErrorType 协议

enum MyError: ErrorType{
    case Null
    case DivisionByZero
}

然后,您可以使用 throw

调用您的错误
throw MyError.DivisionByZero

因此,除法函数可能如下所示

func divide(x: Int, y: Int) throws -> Float{
    if(y == 0){
        throw MyError.DivisionByZero
    }
    else{
        return x / y
    }
}

根据 Swift 文档:

Throwing Errors

To indicate that a function or method can throw an error, you write the throws keyword in its declaration, after its parameters. If it specifies a return type, you write the throws keyword before the return arrow (->). A function, method, or closure cannot throw an error unless explicitly indicated.

Apple's documentation

中有大量关于此主题的信息

错误是使用枚举表示的,因此通过枚举创建一些您想要的错误,然后使用 throw 关键字来完成。

示例:

enum MyError: ErrorType{
    case FooError
}

func foobar() throws{
   throw MyError.FooError
}