5th Week of Swift — for in, while, and optional
More than one condition
var age = 18
var weight = 45
if var age < 30 {
if var weight < 50 {
var message = "你是我的傳說"
}}
else {}
&&
var age = 18
var weight = 45
if var age < 30 && var weight < 50 {
var message = "你是我的傳說"
}
else {
var message = "太老又太胖"
}
||
OR, when one of condition satisfied, the program can work)
var age = 35
var weight = 45
if age < 30 || weight < 50 {
var message = "你是我的傳說"
}
else {}
!
means opposite
The order of reading code
- From left to right
var age = 35
var weight = 45
var height = 160
if age < 30 || weight < 50 && height < 170 {
var message = "你是我的傳說"
}
else {}
- In this situation, not taller than 170, either age < 30 or weight < 50 is accepted.
LOOP
How to express var sum = 1 + 2 + 3 + 4+….+ 1000 ??
→ 1..< 3 , including 1, 2
→1…3, including 1, 2, 3
- for + name of constant + in + a range of number or other set operation
var sum = 0
for i in 1...1000 {
sum = sum + i
}
Practice
Q1: sum up 1 to 1000 and only with even number (hint: for in &)
var sum = 0
for i in 1...1000 {
if i % 2 == 0
sum = sum + i
}
2. while ( suitable for those the variable is not clear)
- Variable has to be declared in advance, while “for in” is not essential
var number = 0
while number < 10 {
number = number - 1
}
Practice
Q1: 1² + 2² + 3² +…+99²

Q2:2²+4²+6²+…+100²


Comment
- for single line: //
- more than one line comment: /*, */
Optional
- Can be lack of information
- nil: means empty
var age: Int?
var age:Int? = nil
- Read the information in optional: add!
var age:Int? = 18
age = age! + 1
- Check whether there is information in optional
var age:Int? = 18
if age != nil {
age = age! + 1
}
Optional binding
if + let + constant number + = + optional
var age: Int? = 18
if let ageNumber = age {
age = ageNumber + 1
}
else {
}
- Can use the same name in optional binding
var age:Int? = 18
if let age = age {
age = age + 1
else {
}
Implicitly Unwrapped Optionals
- Without using ! to unwrapp the optionals
- Suitable for in which the situation are most with information in optionals
var age:Int! = 18
age = age + 1
- But it could happen when the optional is empty, there will be crash
- So by using if to check is safer ( optional binding is unnecessary)
var age:Int! = 3
if age != nil {
var number = age * 10
}