Numbers and Booleans; Type Safety and Type Inference

So, yes I am on much more of a roll now! The most consistent entries since starting this blog! As before, the issue will be, once the recap/consolidation process is complete, trying to stick to learning new aspects regularly will be the challenge. Anyway, we're cracking on with numbers and booleans first of all....

Numbers and Booleans 

One of the concepts mentioned are floats - numbers which can have decimal places. I know that these are known as 'doubles' and tend to use these over 'floats'. And that's what he goes on to say! Indeed, Pasan explains that Double is preferable as it can store more basically. A lot of this is linked to type inference to e.g. if I declare a variable and give it 3.4 as a value, it will automatically make it of type Double.

Booleans - now these are essentially true or false. String Interpolation - as a reminder - allows values from different types to be put in together. You can create a string made up of a mixture of other types.

Type Safety

I can imagine what this is going to be about. When a variable is declared as a certain type, it will ALWAYS be that type! This avoids errors being made e.g. if I have an int multiplied by a double, I would have to make the int a double. Simple stuff really!

The compiler uses 'Type Checking'. We can actually specifically declare the type that a variable holds. E.g. I could have var number: Double = 3.4. Or var sentence: String = "This is a string."

So Swift can deduce the type - it doesn't need you to declare the type! So should you declare the type explicitly at all? Pasan reckons that this is a matter of balance. Balancing readability with language features. In my mind, it makes sense to let Swift deduce the type.

let firstValue = 4

let secondValue = 6

let output = "The product of \(firstValue) and \(secondValue) is \(firstValue * secondValue)"

let product = firstValue * secondValue


let newOutput = "The product of \(firstValue) and \(secondValue) is \(product)"

In the challenge above, both worked! However the second solution (the correct one) is admittedly more elegant!

Will be pushing ahead with the next videos on Saturday - will be spending at least an hour or two on my recap and consolidation then! 

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)