2
2
.
.
1
1
.
.
8
8
E
E
r
r
r
r
o
o
r
r
s
s
a
a
s
s
s
s
e
e
r
r
t
t
If condition is FALSE, terminate Program and print defined message.
Else continue with the next statement.
assert
var state = 1
assert(state == 1, "There was an eror.") //If FALSE terminate Program with Message.
print("No error")
g
g
u
u
a
a
r
r
d
d
If Condition is FALSE, execute Body (which must return from function or throw error).
Else continue with the next statement.
guard
//DECLARE FUNCTION.
func test(state: Int) {
//IF TRUE CONTINUE WITH NEXT STATEMENT.
guard (state == 1) else {
print("There was an eror.")
return
}
//DISPLAY TEXT.
print("All is good")
}
//CALL FUNCTION.
test(state: 1)
d
d
o
o
.
.
.
.
.
.
c
c
a
a
t
t
c
c
h
h
Inside do block use try keyword to call Function that can throw error.
If Function throws error program jumps to catch block that relates to the thrown error.
do...catch
//DECLARE ENUMERATOR WHICH CAN BE USED TO THROW EXCEPTIONS.
enum VendingMachineError : Error {
case InvalidSelection
case InsufficientFunds(coinsNeeded: Int)
}
//DECLARE FUNCTION WHICH CAN THROW EXCEPTION.
func canThrowErrors() throws -> String {
var error = 2
if (error==1) { throw VendingMachineError.InvalidSelection }
if (error==2) { throw VendingMachineError.InsufficientFunds(coinsNeeded: 5) }
}
//DECLARE DO-CATCH BLOCK.
do {
try canThrowErrors() //Call function that can throw exception.
print("This line is skipped")
}
catch VendingMachineError.InvalidSelection {
print("InvalidSelection")
}
catch VendingMachineError.InsufficientFunds {
print("InsufficientFunds")
}