Day 12 – Optionals

[cc_swift width=”100%” height=”100%”] // optionals var age: Int? = nil // unwrapping optionals /// if let var name: String? = nil if let unwrapped = name { print(“\(unwrapped.count) letters.”) } else { print(“Missing name.”) } /// guard let //// essentially, if it finds nil, it will execute the code inside, and //// expects you to exit the loop or function you created it in. If there //// is a value however, it lets you use it even after guard, like so: func greet(_ name: String?) { guard let unwrapped = name else { print(“Nothing of value here.”) return } print(“Hello, \(unwrapped)! You do have value.”) } greet(nil) greet(“Jack”) // force unwrapping let str = “3” let num = Int(str)! // not an optional, even though it normally would be // implicitly unwrapped optionals // basically optionals which are ‘automatically’ unwrapped, that is, you // don’t need to unwrap them yourself even though they *are* optionals. // you don’t need to use iflet or guardlet but they will crash your code if // you try to read them while they’re nil. let year: Int! = nil // nil coalescing // we might have a function that returns an optional. In this case, we can // specify a default value to be returned in case of ‘nil’, like so: func username(for id: Int) -> String? { if id == 1 { return “Taylor Swift” } else { return nil } } username(for: 15) ?? “Anonymous” // optional chaining let names = [“John”, “Paul”, “George”, “Ringo”] let beatle = names.first?.uppercased() // failable initializers struct Person { var id: String init?(id: String) { if id.count == 9 { self.id = id } else { return nil } } } // typecasting class Animal { } class Fish: Animal { } class Dog: Animal { func bark() { print(“Woof!”) } } let pets = [Fish(), Dog(), Fish(), Dog()] for pet in pets { if let dog = pet as? Dog { //if it’s not dog, it will return nil dog.bark() } } [/cc_swift]

Leave a Reply

Your email address will not be published. Required fields are marked *