optional, error, codable model
Int?
nil
Unwrap is to transform Int? to Int
Int
let num: Int? = ... // num is an Optional Int if num != nil { let unwrappedNum = num! // Forced unwrap to type Int }
if-let
if let unwrappedNum = num { // unwrappedNum is a new copy }
if let num = num { // num is a new copy }
if let num { // num is a new copy }
do-try-catch to handle a possible error
do-try-catch
do { try funcThatCanThrowError() } catch { print(error) }
try! funcThatCanThrowError() // Forced try! _ = try? funcThatCanThrowError() // Maybe.. if not nil
throws the error back to the caller
throws
func iAmNotHandling() throws -> Bool { try funcThatCanThrowError() // Note: Not handled in do-try-catch }
enum PrinterError: Error { case outOfPaper, noToner } func iCanThrowError() throws -> Bool { throw PrinterError.outOfPaper }
Error
Encodable
func encode(to: Encoder) throws
extension MyType: Encodable { func encode(to: Encoder) throws { // My implementation } }
You can extend any type to provide additional func
An easy way to store (and restore) a type.
struct Animal: Codable { var numberOfLegs: Int }
Refer to Codable