Boolean

We are gonna look at Boolean, which stores either true or false.

let number1 = 120
print(number1.isMultiple(of: 3))

let filename1 = "paris.jpg"
print(filename1.hasSuffix(".jpg"))

Both ‘isMultiple(of:_)’ and ‘ hasSuffix’ return a new value based on their check the string has the suffix or it doesn’t. in both places there’s always a simple “true or false answer, which is where Booleans come in. they store just that, and nothing else.

var gameOver = false
print(gameOver)

Booleans have only one special operator, !, which mean “not”. this flips a Boolean’s value from true to false, or false to true.

var something = false
something = !something
print(something)

that will print ‘true’ then ‘false’ when it runs, because something started as false, and we set it to not false, which is true. Now Let’s flip it again

something = !something
print(something)

Now that prints ‘false’. Booleans have a little extra functionality that we call ‘.toggle()’

var gamesOver = false
print(gameOver)

gameOver.toggle()
print(gameOver)

That will print false, then after calling .toggle() will print true. that’s the same as using !


How to join strings together. use + to do it.

let firstPart = "Hello, "
let secondPart = "world!"
let greeting1 = firstPart + secondPart
print(greeting1)

we can do this many times

let people = "Good people"
let action = "love each other"
let lyrics = people + " gonna " + action
print(lyrics)

String interpolation, How to put “Code” inside a String

Put (code) in the String we gonna use string interpolation now. Becasue it’s much more efficient than using +. we could create one sting constant and one integer constant, then combine them into a new string

let myName = "Joseph"
let age = 56
//let message = "Hi, my name is" + myName + "and I'm" age "years old."    -not good.
let message = "Hi, my name is \(myName) and I'm \(age) years old."
print(message)
print("Hello \(2+3) world")
print("The result of 4 + 5 = \(4 + 5)")
Hello 5 world
The result of 4 + 5 = 9


we can put calculations inside string interpolation if we want to.

print("5 x 5 is \(5 * 5)")


[Checkpoint!]

We’re gonna convert temperatures from Celsius to Fahrenheit. Your goal is to write code that:

  1. Creates a constant holding any temperature in Celsius.
  2. Converts it to Fahrenheit by multiplying by 9, dividing by 5, then adding 32.
  3. Prints the result for the user, showing both the Celsius and Fahrenheit values.
let celsius = 20.2
let fahrenheit = celsius * 9 / 5 + 32
print("Celsius is \(celsius)°C, and Fahrenheit is \(fahrenheit)°F.") 
//we can use Option + Shift + 8 to get the degrees symbol:°.