Stoping your program on an error

Sometimes you just know that your code is not going to fail. For example, if know you just restocked the cookie jar, you know you will be able to order a cookie. Add:

do {

try bakery.orderPastry(item: "Cookie", amountRequested: 1, flavor: "ChocolateChip")

}

catch { fatalError()

}

Swift gives you a short way to write the same thing:

try! try bakery.orderPastry(item: "Cookie", amountRequested: 1, flavor: "ChocolateChip")

It’s delicious syntax sugar but know that your program will halt if the no error assumption is violated. So, just as with implicitly unwrapped optionals, you need to be extra careful when using try! :]

results matching ""

    No results matching ""