Throwing function
- From general perspective, it’s one of Error handling in Swift. In Swift, error is represented by value type (structs, or enum) and conform to the
Error
protocol. - To mark a function that can throw an error, you mark it with
throws
keyword before the returned valuefunc canThrowErrors() throws -> String func cannotThrowErrors() -> String
- ::When you don’t provide
throws
, you must handle error inside the function itself:: - When calling function that throws error, you should use
do catch
block and usingtry
- When execution is produced an error, it will moved to the catch block
- When you create function that throws error, you can use
guard let
keyword to return early with error specified - Sometimes, you don’t want to handle all the error case, for this you can use
try?
that producesnil
when error
References
Linked Notes:
Explore structured concurrency in Swift
The idea is based on structured programming. The easiest example is if-else statement where it only execute some block of code conditionally while moving from top to bottom.
Working with Codable in Swift
One of the most common task as iOS developer is get the data from server then parse them so it can be presented nicely to user. On iOS we have Codable protocols that allow us to encode and decode data into standard format (e.g JSON or Property List) Usually you...