DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 14/100)

Swift

  • optionals
  • if let
  • guard let ... else
  • ?? and chaining ?.
  • try?
import Cocoa

// ## optionals
/*
 Optionals are like a box that may or may not have something inside.
 var number: Int? = nil
 var name: String? = "hello world"
 */
// 3 ways to unwrap optionals
// 1) if let
var opposites = ["Mario": "Wario", "Luigi":"Waluigi"]
if let marioOpposite = opposites["Mario"] {
    print("Mario's opposite is \(marioOpposite)")
}

var name: String? = "hello world"
if let name = name {
    print("name is \(name)")
}

// 2). guard let ... else
func printSquare(of number: Int?) {
    guard let number = number else {
        print("Missing input")
        return
    }
    print("\(number) x \(number) is \(number * number)")
}
printSquare(of: 4)
// a more general version of guard is:
// guard someArray.isEmpty else { return }.

// 3) ??
let new = opposites["Peach"] ?? "N/A"

let input = ""
let number = Int(input) ?? 0
print(number)

// chaining
/*
 Optional chains can go as long as you want, and as soon as any part sends
 back nil the rest of the line of code is ignored and sends back nil.
 */
// example 1
let names = [String]()
let chosen = names.randomElement()?.uppercased() ?? "No one"
print("Next in line: \(chosen)")

// example 2
struct Book {
    let title: String
    let author: String?
}

var book: Book? = nil
let author = book?.author?.first?.uppercased() ?? "A"
print(author)

// ## use `try?`
/*
 If the function ran without throwing any errors then the optional will
 contain the return value, but if any error was thrown the function will
 return nil.
 */
enum UserError: Error {
    case badID, networkFailed
}

func getUser(id: Int) throws -> String {
    throw UserError.networkFailed
}

if let user = try? getUser(id: 23) {
    print("User: \(user)")
}
// or
let user = (try? getUser(id: 23)) ?? "Anonymous"


// ## checkpoint

/*
 write a function that accepts an optional array of integers, and returns one randomly. If the array is missing or empty, return a random number in the range 1 through 100.
 */

func randomPick(nums: [Int]?) -> Int {
    return nums?.randomElement() ?? Int.random(in: 1...100)
}
print(randomPick(nums: []))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)