Nick Walter Swift 5 Course - Part 2 (lectures 16 to 22)

Yeah! Two days in a row! Plus, I've managed to get in my summary entry of my first proper year of coding! So today, the plan is to get the 'intermediate' level of Nick's course done. Just 20 minutes now then more soon after that!

Start Time - 14:35

Tuples and Sets

A point about UIKit - this is a bunch of code that Apple has created. It means you basically have access to all of that code etc.

Tuples and Sets hold types.

Tuples - a value that holds two or more pieces of information.

var dog = ("Fido", 8)

dog.0


var cat = (name: "Bob", age: 7)

I've done the second bit myself as I know you can put in named parameters, rather than just using the raw data to access e.g. using .0 or .1. 

Ok for sets, if you specify set, like this...

var numbers: Set = [4, 7, 4, 8, 4, 12, 5]

OK! That makes sense syntactically. In the above, the 4 and 5 are only shown once each. 

You can use the .insert method to add numbers and the .contains to return a bool to show true or false. 

Challenge - create a set of favourite foods. Easy!

var favFoods: Set = ["almonds", "bananas", "chicken", "spinach", "almonds"]

I've deliberately put in almonds twice and yes, only one is shown!

Dictionaries

Think of this as a group of tuples. The key-value pair thing is fine. Going to go through this fairly quickly. 

You can make the key-value types explicit or let Swift infer them. As long as that is consistent!

In the output, the order is randomised - it is not alphabetical or numerical or any sort of order. 

Adding/removing etc.  all fine. 

Challenge - create a dictionary for something around in the room. 

var furnitureNos = ["chairs" : 4, "sofas": 1, "tables": 3, "TV": 1

Easy peasy. Nothing new here. 

Paused at 14:53 (18 minutes so far). 

OK to be spending time recapping; it's useful to go over the basics periodically. I know that with some of the content coming up I will trip a bit but that's all fine. 

Restart at 17:01

Functions

Again, just skimming through as this is just the basics really. 

func sayHello(name: String) {
    
    print("Hello \(name)!")
}

sayHello(name: "Buffy")

You can have more than one parameter. E.g. for adding two numbers, or multiple numbers.

I'm ignoring most of what Nick is saying as that it is all very familiar. Here's my own - 

func sumOf(numbers : Int...) -> Int {
    
    var total = 0
    
    for x in numbers {
        total += x
    }
    
    return total
}

sumOf(numbers: 3, 4, 6, 7, 12)

Challenge - create a function that takes an Int and a string and prints the string the number of times that the int shows. 

func printString(string: String, number: Int) {
    
    for _ in 1...number {
        print(string)
    }
}

printString(string: "Hey!", number: 3)


Done! Functions are fine. 

Optionals

This has always been a tricky area for me. So far, it's just the basics with the use of the ? etc.  They either contain a value or nil. You have to be either 100% sure that there is a value OR unwrap it. 

We need optionals as is protects the program - it can't compute certain errors e.g. when expecting an int, a string being used. 

Use of ! As force unwrapping. I've heard mixed things - some programmers say NEVER use this. Others say that in certain situations you have to. The general rule is not to use it, unless you are 100% sure and that there is literally NO CHANCE for it NOT to have that value!

Challenge - 



func checkString(text: String?) {
    
    if text == nil {
        print("IT IS NIL!")
    } else {
        print(text!)
    }
}

Ok, I missed something! I was doing the double equals instead of one and was wondering why the below wasn't working. Now I've tweaked it, it does!

func checkString(text: String?) {
    
    if let checkText = text {
        print(checkText)
    } else {
        print("IT IS NIL!")
    }
}

Classes

Blueprints - which then create objects, which can then be used. I think of them as being bundles of information.

Two things can go in - properties or functions. 

Properties - these are what describe the dog
Functions - these show behaviour - what the dog can do

class Dog {
    
    var name = ""
    var age = 0
    var colour = ""
}

var myDog = Dog()

myDog.age

In this example, you can change the values of the properties e.g. myDog.name = "Bruce" etc. 

This is a very basic way of making a class - this is separate to doing it with initialization. 

Challenge - 

Make a class based on something in the room (lame!). 

class Television {
    var length = 0
    var width = 0
    var colour = true
    var location = "Living room"
    
    func makeNoise() {
        
        print("Zip!")
    }
    
    func whereIsTelevision() {
        print("The TV is in the \(location)")
    }
}

That was easy. Again, classes without using the init part are easy!

Structures

These are very similar to classes. One key thing is the init phase isn't needed. The other is about the memory - a struct is a value type whereas classes are reference type. The value is a straight up type that is there and does not change. A reference type can change...that is still a bit of a mystery to me and Nick does not even attempt to explain it at this stage!

Upon creation of the object e.g. myDog, I can then put all of the values in! This is the init part which I mentioned. 

struct Character {
    
    var name: String
    var age: Int
    var alive: Bool
    var favWeapon: String
}

var buffy = Character(name: "Buffy", age: 23, alive: true, favWeapon: "Stake")

When creating the object, you put all the values in like above. If one of those is already done within the struct, then you can't create them as part of initialisation. 

No scrap that. You can! 

struct Character {
    
    var name: String
    var age: Int
    var alive = true
    var favWeapon = "Stake"
}

//var buffy = Character(name: "Buffy", age: 23, alive: true, favWeapon: "Stake")

var willow = Character(name: "Willow", age: 22, alive: true, favWeapon: "Spell book")

It's if a CONSTANT were used. I've changed favWeapon to a constant; now the option does not even come up! Cool.


var cordelia = Character(name: "Cordelia", age: 23, alive: false)


Challenge - make a struct of something in the room... again a lame idea Nick!

struct Sofa {
    var colour: String
    var width: Int
    var length: Int
    var hasCushions: Bool
    var age: Int
}


Enums

Nick likens these to multiple choice options. Cool - that's exactly as I see them too! North, South, East, West...seasons, planets...finite options are best!

enum Compass {
    case north, south, east, west
}

var direction : Compass = .north

He then makes a function which refers to the enum...


I would use a switch statement for this rather than a function. 

OK, so an example to combine all of this together. 

enum FurColour {
    case brown, black, golden, white
}

class Dog {
    
    var name = ""
    var age = 0
    var colour = ""
    var furColour: FurColour = .black
    
    func bark() {
        print("Woof!")
    }
    
    func barkDetails() {
        print("My name is \(name) and I am \(age) years old")
    }
}



var newDog = Dog()

newDog.furColour = .brown

*Paused for approx 20 minutes

So that's all for today! Managed to cover a lot - and all worthwhile! Tomorrow I will finish this part of the intermediate. 

Total Time - approx 1 hour 30 minutes

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)