15.3 Throwing an Error
A method or function declares that it can throw an error using the throws keyword. For example:
func transferFile() throws {
}
In the event that the function or method returns a result, the throws keyword is placed before the return type as follows:
func transferFile() throws -> Bool {
}
Once a method has been declared as being able to throw errors, code can then be added to throw the errors when they are encountered. This is achieved using the throw statement in conjunction with the guard statement. The following code declares some constants to serve as status values and then implements the guard and throw behavior for the method:
let connectionOK = true
let connectionSpeed = 30.00
let fileFound = false
enum FileTransferError: Error {
case noConnection
case lowBandwidth
case fileNotFound
}
func fileTransfer() throws {
...