Enumerations & Optionals - final part

Well, I haven't been able to maintain my every/most day but to be fair, two missed days is not the end of the world! Optionals and Enumerations are still pretty fresh in my head. I've used 'Swifty' to consolidate my understanding and go over a few concepts. This next blog should be the last one in the Optional/Enum course. 

Raw Values

Enums can store different types. Enum members can be populated with default - raw - values.


enum Coin {
    
    case penny
    case nickel
    case dime
    case quarter
}

let coins: [Coin] = [.penny, .nickel, .dime, .dime, .quarter, .quarter, .quarter]

func sum (having coins: [Coin]) -> Double {
    
    var total: Double = 0
    
    for coin in coins {
        
        switch coin {
            
        case .penny: total += 0.01
        case .nickel: total += 0.05
        case .dime: total += 0.1
        case .quarter: total += 0.25
        }
    }
    
    return total

}
This is what we have created so far. The enum has cases of different coins, then an array is created with a combination of these. Next, a function is used, to return the value of the coins, based on the switch cases below. Pasan describes this as long-winded!

Instead of this, default values can be given!

enum Coin: Double {
    
    case penny = 0.01
    case nickel = 0.05
    case dime = 0.1
    case quarter = 0.25
}
Raw values are not associated values. You use Raw values when you always want these values. Associated change. Raw values cannot have custom types - just int, double, float, string and character. 

func sum (having coins: [Coin]) -> Double {
    
    var total: Double = 0
    
    for coin in coins {
        
       total += coin.rawValue
    }
    
    return total
}

Also with this example, the switch statement is not needed, as .rawValue can be accessed. That's much simpler indeed!

enum Day: Int {
    
    case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
    
}

This is clever and I picked it up in that Udemy course - Swift infers that I want a sequence of numbers - in this case, ints, from 1 up to 7. 

enum HTP: String {
    
    case post
    case get
    case put
    case delete
}

HTP.delete.rawValue

Nice...so for a string enum, the string of that case word is used as the default. Clever!

Initializing with Raw Values

enum HTTPStatusCode: Int {
    
    case success = 200
    case forbidden = 403
    case unauthorised = 401
    case notFound = 404
}

This is all for checking a status code to connect to the web....


let statusCode = 200

let httpStatusCode = HTTPStatusCode(rawValue: statusCode)

So, here we have created a constant, then another one to check the status...An optional is actually returned here....It's because there is a CHANCE OF FAILURE!

Optional Chaining

class Address {
    
    var buildingName: String?
    var buildingNumber: String?
    var street: String?
}

class Residence {
    
    var numberOfRooms = 1
    var address: Address?
}

class Person {
    
    var residence: Residence?
}

OK, interestingly, no init methods are used and there are no errors! This is because OPTIONALS are used. 



let susan = Person()

let address = Address()

address.street = "1234 Something Drive"

address.buildingName = "Building"

address.buildingNumber = "10"

let residence = Residence()

residence.address = address

susan.residence = residence

if let home = susan.residence, let postalAddress = home.address, let buildingNumber = postalAddress.buildingNumber, let convertedNumber = Int(buildingNumber) {
    print(convertedNumber)
}

let buildNumber = susan.residence?.address?.buildingNumber

This is VERY complicated! Pasan shows an animation where a train travels along to check if there is nil at each stage - if there is nil, then nil is returned. Combining optional binding and chaining in one go is the best way...

if let buildingNumber = susan.residence?.address?.buildingNumber {
    print(buildingNumber)
}

It is apparently going to be useful in future choices. I'm getting my head around it but still bot 100% sure. 

Pattern Matching

enum Coin: Double {
    
    case penny = 0.01
    case nickel = 0.05
    case dime = 0.1
    case quarter = 0.25
}

let wallet: [Coin] = [.penny, .nickel, .dime, .penny, .dime, .quarter, .nickel, .nickel, .penny, .quarter]

var count = 0

for coin in wallet {
    
    switch coin {
    case .quarter: count += 1
    default: continue
    }
}

for coin in wallet {
    
    if case .nickel = coin {
        
        print("Not much money my friend!")
    } else if case .dime = coin {
        print("Could be worse!")
    }
}

Nil Coalescing Operator

let firstName: String? = "Josh"
let username = "RoganJosh"

var displayName: String

if let name = firstName {
    
    displayName = name
} else {
    
    displayName = username
}

This is to check if something has a certain value - with two options to choose between....

var displayName = firstName ?? username

This is very succinct! This ternary condition operator - used with an optional value. Pasan says to always start with an if statement. 

So that's all of optionals and enumerations...phew! Definitely the trickiest so far, but Pasan made some good points in the conclusion video. First of all, optionals are a concept - I don't need to know all of the syntax off by heart. I definitely get now the benefits of optionals and how it's useful to have a value that may be nil. In an app/program, it is powerful for this to be the case, whether it's in a database of information or a list of numbers where not all of them can hold values. Anyway, I get that side to it. Enumerations are tricky but I've learned a lot about them - how you can have default values, how you can have certain types, how associated values are used...there's a lot to them and it's exciting to think that I could link this to an F1 game - how the cases could be outcomes at a corner, types of skills...so many possibilities! Next course for me is building a simple iPhone app - it's about time I got back to the main Xcode program and got my head around all of the layout there. Anyway, I did more to do to make up for the fact I missed two whole days. Back tomorrow!

Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)