Swift Control Flow
Control Flow - For-In Loops, While Loops, Conditional Statements
1. For-In Loops π©βπ»
For-In
λ°λ³΅λ¬Έμ Array κ° μ μ₯ν items
, String μ΄ μ μ₯ν characters
μ κ°μ sequence
λ₯Ό λ°λ³΅ν μ μλ€.
1. Iterate over with numeric ranges
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
1 times 5 is 5
2 times 5 is 10
3 times 5 is 15
4 times 5 is 20
5 times 5 is 25
- λ§μ½, μμλ₯Ό μΈμλ‘ λ°μ νμκ° μλ€λ©΄
_
λ₯Ό μ΄μ©ν΄ μ±λ₯μ ν₯μμν¬ μ μλ€
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)") // 3 to the power of 10 is 59049
stride(from:to:by:)
λ₯Ό μ΄μ©νλ©΄from..<to
λ²μλ₯Όby
λ§νΌ stepμ λ£μ΄ sequenceλ₯Ό λ§λ€ μ μλ€
let sequence = stride(from: 0, to: 60, by: 5)
print(type(of: sequence)) // StrideTo<Int>
for tickMark in stride(from: 0, to: 60, by: 5) {
print(tickMark, terminator: " ") // 0 5 10 15 20 25 30 35 40 45 50 55
}
2. Iterate over the items in an array
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
Hello, Anna!
Hello, Alex!
Hello, Brian!
Hello, Jack!
3. Iterate over a dictionary to access its key-value paris
μ°λ¦¬λ Iterating over a dictionaryμμ μ΄ν΄λ³Έ κ² μ²λΌ Dictionary λ ν μμ
Kye: Value elements λ₯Ό tuple
λ‘ μ κ·Όν΄ λ°λ³΅ν μ μλ€.
μλλ animalName
μ΄λΌλ Key constant μ legCount
λΌλ Value constant λ₯Ό κ°λ tuple λ‘ λΆν΄λλ μμ λ€.
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
cats have 4 legs
spiders have 8 legs
ants have 6 legs
2. While Loops π©βπ»
μ°μ μλ while
μ μ€λͺ
νλ©΄μ μ¬μ©ν μ£Όμ¬μ ν¨μλ λ€μκ³Ό κ°λ€.
func rollDice() -> Int {
Int.random(in: 1...6)
}
1. While
while λ°λ³΅λ¬Έμ μ‘°κ±΄μ΄ false
κ° λ λκΉμ§ λ°λ³΅μ κ³μνλ€. μ΄κ²μ loop κ° μμλ λ μ νν λ°λ³΅ νμλ₯Ό μ μ μλ κ²½μ° μ μ©νκ² μ¬μ©λ μ μλ€.
Syntax
while condition {
statements
}
Q) μ£Όμ¬μλ₯Ό 2κ° κ΅΄λ € κ³±ν κ°μ΄ 20 μ΄μμ΄λ©΄ λ°λ³΅λ¬Έμ μ€μ§νλΌ.
-> λ°λ³΅ νμλ₯Ό μ μ μλ€.
-> while μ¬μ©μ΄ μ ν©νλ€.
var result = 0
var rollCount = 0
while result < 20 {
result = rollDice() * rollDice()
rollCount += 1
print(result)
}
print("The dice are rolled \(rollCount) times.")
10
4
36
The dice are rolled 3 times.
2. Repeat-While
repeat-while
μ΄ while
κ³Ό λ€λ₯Έ μ μ λ°λ³΅ν λ‘μ§μ λ¨Όμ μ€ν ν 쑰건μ κ²μ¬νλ€. κ·Έλ κΈ° λλ¬Έμ repeat-while
μ
μ΅μν 1λ²μ λ‘μ§μ μννλ€.
Syntax
repeat {
statements
} while condition
μ μ£Όμ¬μ λ¬Έμ μμ result μ μ΄κΉκ°μ΄ 20λ³΄λ€ ν¬κ² μ ν΄μ Έ μλ€κ³ κ°μ ν΄λ³΄μ.
var result = 25
var rollCount = 0
while result < 20 {
result = rollDice() * rollDice()
rollCount += 1
print(result)
}
μ λ‘μ§μ 첫 condition μ΄ false
μ΄λ―λ‘ while λ΄λΆλ μ€ννμ§ μλλ€.
μ΄λ²μλ μ λ‘μ§μ repeat-while
λ‘ λ°κΏμ μ€νν΄λ³Έλ€.
var result = 25
var rollCount = 0
repeat {
result = rollDice() * rollDice()
rollCount += 1
print(result)
} while result < 20
print("The dice are rolled \(rollCount) times.")
1
3
18
4
24
The dice are rolled 5 times.
μ΄κΉκ°μ΄ 20 μ΄μμ΄μ§λ§ μ΅μ΄ 1ν μ€νμ νλ€. κ·Έλ¦¬κ³ μ΄λ κ³μ°λ result λ condition μ λ§μ‘±νλ μμ κ°μΌλ‘ λ°λ κ²½μ°
repeat
μ λ°λ³΅νκ²λλ€. λ°λΌμ Repeat-While
μ μ΅μ 1λ²μ μ€ννλ―λ‘ 1 ~ nλ²μ λ°λ³΅μ νκ² λλ€.
3. While-True
μ¬κΈ° μ‘°κΈ νΉλ³ν λ°©μμ While
λ¬Έμ΄ μλ€.
While λλ Repeat-While μ λ°λ³΅μ κ³μν μ§ μ¬λΆ
λ₯Ό true/false λ‘ condition
μ λ£μ΄ λ°λ³΅ μ¬λΆλ₯Ό κ²°μ νλ€.
λ°λ©΄ While-True
λ condition μ νμ true λ₯Ό μ£Όκ³ , λ°λ³΅μ μ€λ¨ν μ§ μ¬λΆ
λ₯Ό if λ‘ κ²μ¬ν΄ μ 체 While
λ¬Έμ νμΆνλ€. λ°λΌμ,
μΌλ°μ μΈ While, Repeat-While 쑰건μ λ°λ(!condition)κ° λλ€
(λ§μ½, Logical NOT Operator(!
) λμ λ
Όλ¦¬μ μΌλ‘ λ°λμ μΌμ΄μ€λ₯Ό λ£μ μ μλ€λ©΄ κ·Έλ κ² νλ κ²μ΄ μ±λ₯μ μ΄μ μ κ°λλ€).
Syntax
while true {
statements
if !condition {
break
}
}
- !condition
var result = 25
var rollCount = 0
while true {
result = rollDice() * rollDice()
rollCount += 1
print(result)
if !(result < 20) {
break
}
}
- else break
var result = 25
var rollCount = 0
while true {
result = rollDice() * rollDice()
rollCount += 1
print(result)
if result < 20 {
} else {
break
}
}
print("The dice are rolled \(rollCount) times.")
- logical opposite condition
var result = 25
var rollCount = 0
while true {
result = rollDice() * rollDice()
rollCount += 1
print(result)
if result >= 20 {
break
}
}
print("The dice are rolled \(rollCount) times.")
Repeat-While
λ‘μ§μ΄ μλ μΈμ΄μΌ κ²½μ° μ΄λ°μμΌλ‘ ꡬνν μ μμ§λ§, Swift λ μ΄λ₯Ό μ§μνλ―λ‘ λͺ νν μ½λ μλ μ λ¬ λ° κ°λ μ±μ μν΄Repeat-While
λ‘ μ½λλ₯Ό μμ±νλ κ²μ΄ μ’λ€.
3. Conditional Statements - If π©βπ»
Swift λ 쑰건μ λ°λΌ λ€λ₯Έ λ‘μ§μ μνν μ μλλ‘ If
μ Switch
λ₯Ό μ 곡νλ€. κ·Έ μ€ If
λ₯Ό μμλ³Έλ€.
1. Single if
statement
if λ μ‘°κ±΄μ΄ λ§μ‘±λ λ μ€ννλ λ‘μ§μ μ μν μ μλ€.
let temperatureInCelsius = 32
if temperatureInCelsius > 28 {
print("It's hot. Turn on the air conditioner.")
}
// It's hot. Turn on the air conditioner.
2. if
statements with else
clause
else
clause λ₯Ό μ΄μ©ν΄ if
statement μ 쑰건μ λ§μ‘±νμ§ μμ κ²½μ°μ μ€ννλ λμ λ‘μ§μ μ μν μ μλ€.
let temperatureInCelsius = 24
if temperatureInCelsius > 28 {
print("It's hot. Turn on the air conditioner.")
} else {
print("It's nice weather. Go out for a walk.")
}
// It's nice weather. Go out for a walk.
3. Chaining multiple if
statements
else if
λ₯Ό μ΄μ©ν΄ μ¬λ¬ κ°μ if 쑰건μ μ°μμ μΌλ‘ κ²μ¬ ν μ μλ€. μ΄ λ λ§μ‘±νλ if λ₯Ό λ§λλ©΄ λ‘μ§μ μν ν νμΆνλ€.
let temperatureInCelsius = 3
if temperatureInCelsius > 28 {
print("It's hot. Turn on the air conditioner.")
} else if temperatureInCelsius < 10 {
print("It's cole. Turn on the boiler.")
} else {
print("It's nice weather. Go out for a walk.")
}
// It's cole. Turn on the boiler.
else
clause λ μΈμ λ Optional μ΄κΈ° λλ¬Έμ νμκ° μλλ€.
4. Conditional Statements - Switch π©βπ»
Swift λ 쑰건μ λ°λΌ λ€λ₯Έ λ‘μ§μ μνν μ μλλ‘ If μ Switch μ 곡νλ€. κ·Έ μ€ Switch
λ₯Ό μμλ³Έλ€.
1. Alternative to the if statement for multiple states
μ¬λ¬ κ°μ condition
μ΄ μ£Όμ΄μ§λ κ²½μ° if ~ else if ~ else if ... else
λ switch
λ¬ΈμΌλ‘ λ체 ν μ μλ€.
Syntax
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// The last letter of the alphabet
if statement μμ else
λ μΈμ λ Optionalμ΄μ§λ§ switch λ¬Έμμ default
λ
νμλ€.
λ°λΌμ if λ₯Ό switch λ‘ λ°κΏ λ else λ₯Ό ꡬννμ§ μλ κ²½μ°λ default
μ break
λΌλ λ£μ΄μ€μΌνλ€.
let someCharacter: Character = "u"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
break
}
// Nothing
TypeScript(JavaScript)
μ κ°μ λ€λ₯Έ μΈμ΄μμλdefault
κ°Optional
μΈ κ²½μ°κ° μμΌλ Swift μμλ νμλ‘ κ΅¬νν΄μΌνλ€.
TypeScript λ default κ° Optional μ΄λΌ ꡬννμ§ μμλ λλ€.
const anotherCharacter: string = "u" switch (anotherCharacter) { case "a": console.log("The first letter of the alphabet") break case "z": console.log("The last letter of the alphabet") break } // Nothing
2. No Implicit Fallthrough
Objective-C λ₯Ό ν¬ν¨ν λλΆλΆμ μΈμ΄μμ switch μ μλμ μ²μ μΌμΉνλ case λ₯Ό μ€νν ν μλ case λ₯Ό
κ³μ μ€νν΄ λ΄λ €κ°λ€(fallthrough
the bottom of each case).
const anotherCharacter: string = "z"
switch (anotherCharacter) {
case "a":
case "A":
console.log("The first letter of the alphabet")
break
case "z":
case "Z":
console.log("The last letter of the alphabet")
break
}
// The last letter of the alphabet
Swift μ switch λ¬Έμ μ²μ μΌμΉνλ case λ₯Ό μ€νν ν μ¦μ μ’
λ£
λλ€.
λ°λΌμ Swift μμ μλμ κ°μ λ‘μ§μ μ»΄νμΌ μλ¬κ° λ°μλλ€.
let anotherCharacter: Character = "z"
switch anotherCharacter {
case "a": // 'case' label in a 'switch' must have at least one executable statement
case "A":
print("The first letter of the alphabet")
case "z": // 'case' label in a 'switch' must have at least one executable statement
case "Z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
λ°λΌμ Swift μ switch λ¬Έμ βbreakβλ₯Ό λͺ
μνμ§ μμλ λλ€.
λ°λλ‘ μλμ μΌλ‘ fallthrough μν€κΈΈ μνλ©΄ fallthrough
λ₯Ό λͺ
μν΄μΌνλ€.
let anotherCharacter: Character = "z"
switch anotherCharacter {
case "a": fallthrough
case "A":
print("The first letter of the alphabet")
case "z": fallthrough
case "Z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// The last letter of the alphabet
νμ§λ§ μμ κ°μ λ°©μμ κΆμ₯λμ§ μλλ€. Swift λ μΌμΉνλ case λ₯Ό μ€ν ν μ¦μ μ’
λ£ν¨μΌλ‘μ¨ λλΆλΆμ κ²½μ° κ°λ°μκ° switch λ¬Έμμ
break λ₯Ό λΉ λ¨λ € λ°μνλ λ
Όλ¦¬μ μ€λ₯λ₯Ό μλ°©ν λΏ μλλΌ λ€λ₯Έ μΈμ΄μμ single case match
λ§ λ§€μΉν μ μλ κ²κ³Ό λ¬λ¦¬
multiple case match
λ₯Ό νλ―λ‘ λλμ± fallthrough λ νμκ° μλ€.
μ΄κ²μ Compound Cases λΌ νλ©° μλμ λ€μ λ€λ£¨λλ‘ νλ€.
let anotherCharacter: Character = "z"
switch anotherCharacter {
case "a", "A":
print("The first letter of the alphabet")
case "z", "Z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// The last letter of the alphabet
κ°λ μ±μ μν΄ multiple case λ₯Ό μ€λ°κΏ ν΄ λ§€μΉν μ μλ€.
3. Switch-True
μ¬κΈ° μ‘°κΈ νΉλ³ν λ°©μμ Switch
λ¬Έμ΄ μλ€.
1 ) Interval Matching
μΌλ°μ μΌλ‘ Switch λ¬Έμ equal
λ‘ λ§€μΉλκΈ° λλ¬Έμ single case match
κ° κΈ°λ³Έμ΄λ€. λ°λΌμ λ²μ 맀μΉμ μλμ κ°μ΄ μμ±νλ€.
const approximateCount: number = 62
const countedThings: string = "moons orbiting Saturn"
let naturalCount: string
switch (true) {
case approximateCount === 0:
naturalCount = "no"
break
case (approximateCount >= 1) && (approximateCount < 5):
naturalCount = "a few"
break
case (approximateCount >= 5) && (approximateCount < 12):
naturalCount = "several"
break
case (approximateCount >= 12) && (approximateCount < 100):
naturalCount = "dozens of"
break
case (approximateCount >= 100) && (approximateCount < 1000):
naturalCount = "hundreds of"
break
default:
naturalCount = "many"
}
console.log(`There are ${naturalCount} ${countedThings}.`)
There are dozens of moons orbiting Saturn.
λ§μ°¬κ°μ§λ‘ Swift λ Interval Matching μ μ¬μ©νμ§ μκ³ λ€μκ³Ό κ°μ΄ Switch-True
λ₯Ό μ΄μ©ν΄ λ²μ 맀μΉμ ν μ μλ€.
let approximateCount: Int = 62
let countedThings: String = "moons orbiting Saturn"
let naturalCount: String
switch true {
case approximateCount == 0:
naturalCount = "no"
case (approximateCount >= 1) && (approximateCount < 5):
naturalCount = "a few"
case (approximateCount >= 5) && (approximateCount < 12):
naturalCount = "several"
case (approximateCount >= 12) && (approximateCount < 100):
naturalCount = "dozens of"
case (approximateCount >= 100) && (approximateCount < 1000):
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
There are dozens of moons orbiting Saturn.
2 ) Validation Check
Switch-True
μ μ©λ² μ€ λ€λ₯Έ νλλ if ~ else if ~ else if ~ ... else
κ΅¬λ¬Έλ³΄λ€ λμ± κ°κ²°νκ² Validation Check
λ₯Ό ν μ μλ€λ κ²μ΄λ€.
struct User {
var name: String?
var age: Int?
var phone: String?
var height: Double?
var weight: Double?
}
func validateUser(of user: User?) -> Bool {
guard let user = user else { return false }
switch true {
case user.age == nil: print("age is nil"); return false
case (user.age! < 0) || (user.age! > 130): print("invalid age"); return false
case user.name == nil: print("name is nil"); return false
case user.phone == nil: print("phone is nil"); return false
case user.height == nil: print("height is nil"); return false
case user.weight == nil: print("weight is nil"); return false
default: return true
}
}
var myUser = User(name: "νκΈΈλ", age: 132, phone: "010-4434-3556", height: 183.2, weight: 74)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
invalid age
Validation check result of myUser is false.
var myUser = User(name: "μ₯λ³΄κ³ ", age: 42, phone: "010-2342-1234", height: 175.2, weight: nil)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
weight is nil
Validation check result of myUser is false.
var myUser = User(name: "μ΄μμ ", age: 30, phone: "010-7423-3464", height: 169.6, weight: 52)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
Validation check result of myUser is true.
μ κ·ννμμ μ΄μ©νκ±°λ,
Bool
κ²°κ³Ό λμException
μthrow
νλλ‘ ν μλ μλ€.
4. Interval Matching
Swift μ switch λ¬Έμ multiple case match
λ₯Ό μ§μνκΈ° λλ¬Έμ Switch-True
λμ range operator
λ₯Ό μ΄μ©ν΄
λμ± κ°κ²°ν μ½λλ‘ λ²μ 맀μΉμ ν μ μλ€.
let approximateCount: Int = 62
let countedThings: String = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
There are dozens of moons orbiting Saturn.
5. Tuples
_
λ whildcard pattern
μΌλ‘ μ¬μ©λμ΄ μ΄λ€ κ°μ΄λ 맀μΉν μ μλ€.
func whereIs(_ point: (Int, Int)) {
switch point {
case (0, 0):
print("\(point) is at the origin")
case (_, 0):
print("\(point) is on the x-axis")
case (0, _):
print("\(point) is on the y-axis")
case (-2...2, -2...2):
print("\(point) is inside the box")
default:
print("\(point) is outside of the box")
}
}
whereIs((0, 0)) // (0, 0) is at the origin
whereIs((3, 0)) // (3, 0) is on the x-axis
whereIs((1, 2)) // (1, 2) is inside the box
whereIs((3, 2)) // (3, 2) is outside of the box
6. Value Bindings
Swift λ switch
ꡬ문μμλ Value Bindings
λ₯Ό μ¬μ©ν μ μλ€.
func anotherPoint(_ point: (Int, Int)) {
switch point {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
}
anotherPoint((4, 0)) // on the x-axis with an x value of 4
anotherPoint((0, 2)) // on the y-axis with a y value of 2
anotherPoint((2, 6)) // somewhere else at (2, 6)
7. Where
Value Bindings
μ where
λ₯Ό μ΄μ©ν΄ μΆκ° 쑰건μ κ±Έ μ μλ€.
func yetAnotherPoint(_ point: (Int, Int)) {
switch point {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
}
μ ν¨μλ₯Ό νμ΄μ°λ©΄ λ€μκ³Ό κ°λ€.
func yetAnotherPoint(_ point: (Int, Int)) {
let (x, y) = point
switch true {
case x == y:
print("(\(x), \(y)) is on the line x == y")
case x == -y:
print("(\(x), \(y)) is on the line x == -y")
default:
print("(\(x), \(y)) is just some arbitrary point")
}
}
yetAnotherPoint((4, 4)) // (4, 4) is on the line x == y
yetAnotherPoint((3, -3)) // (3, -3) is on the line x == -y
yetAnotherPoint((3, 7)) // (3, 7) is just some arbitrary point
λ¨,
where
λ λ¨λ μΌλ‘ μ¬μ©λ μ μκ³ case μValue Bindings
κ° λ μμλ λ³μκ° μμ΄μΌνλ€.
8. Compound Cases
μ No Implicit Fallthrough μμ λ³Έ κ²μ²λΌ Swift μ switch λ
multiple case match
λ₯Ό μ§μνλ―λ‘ μ¬λ¬ μΌμ΄μ€λ₯Ό νΌν©ν΄μ Compound Cases
λ₯Ό μ¬μ©ν μ μλ€.
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
// e is a vowel
Compound Cases μμ Value Bindings λ₯Ό μ¬μ©νλ κ² μμ κ°λ₯νλ€.
func stillAnotherPoint(_ point: (Int, Int)) {
switch point {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
}
// On an axis, 9 from the origin
λ§μ°¬κ°μ§λ‘ μ Switch-True λ₯Ό μ¬μ©ν Validation Checkλ₯Ό λ€μ μ°λ©΄ λ€μκ³Ό κ°μ΄ μ¬μ©ν μλ μλ€.
struct User {
var name: String?
var age: Int?
var phone: String?
var height: Double?
var weight: Double?
}
func validateUserWithCompoundCases(of user: User?) -> Bool {
guard let user = user else { return false }
switch true {
case user.age == nil, user.name == nil,
user.phone == nil, user.height == nil,
user.weight == nil
: print("Something is nil"); return false
case (user.age! < 0) || (user.age! > 130): print("invalid age"); return false
default: return true
}
}
print("Validation check result is \(anotherResult!).")
invalid age
Validation check result is false.
5. Control Transfer Statements π©βπ»
Swift μλ μ½λμ νλ¦μ μ μ΄νλ 5κ°μ§ Control Transfer Statements
κ° μλ€.
- continue
- break
- fallthrough
- return
- throw
1. continue
iteration
μ νμ¬ loop λ₯Ό μ€λ¨νκ³ λ€μ loop λ‘ κ±΄λλ΄λ€
.
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
if charactersToRemove.contains(character) {
continue
}
puzzleOutput.append(character)
}
print(puzzleOutput) // grtmndsthnklk
continue
μ μν΄ λͺ¨μμ΄λ 곡백μ λ§λλ©΄ 건λλ°κ³ μμλ§ μΆλ ₯νλ€.
2. break
iteration
loop λλ switch
μ μ 체 ꡬ문μ μ¦μ μ€λ¨νκ³ νμΆ
νλ€.
- Iteration
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
if charactersToRemove.contains(character) {
break
}
puzzleOutput.append(character)
}
print(puzzleOutput) // gr
- Switch
let someLetter = "B"
switch someLetter {
case "A": print("This character is 'A'.")
case "B": break
case "C": print("This character is 'C'.")
default: break
}
Swift μ Switch λ¬Έμ κΈ°λ³Έμ μΌλ‘
No Implicit Fallthrough
μ΄λ―λ‘breakλ μλ΅
ν΄λ λλ€.
3. fallthrough
Switch
μμ 맀μΉλλ case μ λ€μ caseλ₯Ό μ€ν
νλλ‘ μλμ μΌλ‘ λͺ
λ Ή
νλ€.
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description) // The number 5 is a prime number, and also an integer.
Swift μ Switch λ¬Έμ case 맀μΉμ
break
κ° κΈ°λ³Έ μλ μμμ΄λ―λ‘ λ€λ₯Έ μΈμ΄μ λ¬λ¦¬fallthrough
κ° νμν κ²½μ° λͺ μν΄μΌνλ€.
4. return
break
κ° iteration loop λλ switch μ μ 체 ꡬ문μ μ¦μ μ€λ¨νκ³ νμΆ νλ κ²μ²λΌ return
μ function
λ΄λΆμμ μ¬μ©λμ΄
μ 체 ꡬ문μ μ¦μ μ€λ¨
νκ³ κ°μ λ°ν
νλ€.
λ°λΌμ return
μ΄ μ€νλλ©΄ function λ΄λΆ μ iteration loop
λλ switch
ꡬ문μ λ μμ scope μΈ function μ체κ°
μ’
λ£λλ―λ‘, λ³λμ break μμ΄λ μ€λ¨
λλ€.
5. throw
throw
λ return
κ³Ό λ§μ°¬κ°μ§λ‘ function
λ΄λΆμμ μ¬μ©λμ΄ μ 체 ꡬ문μ μ¦μ μ€λ¨
νκ³ , Error
λλ fatalError
λ₯Ό
λ°ννλ€.
6. Labeled Statements
iteration loop
λ switch
μ κ°μ ꡬ문μ μ€λ³΅ν΄ μ¬μ©ν μ μλ€. μ΄ λ λ‘μ§μ νλ¦μ μ νν μ μ΄νκΈ° μν΄ label
μ΄ νμνκ³ ,
μ΄λ₯Ό labeld statements
λΌ νλ€.
Syntax
label name: while condition {
statements
}
μ£Όμ¬μ 1 μ΄ μ£Όμ¬μ 2 λ³΄λ€ κ°μ΄ ν¬λ©΄ κ²μμ μ’ λ£νλ loop λ₯Ό λ§λ λ€.
func rollDice() -> Int {
Int.random(in: 1...6)
}
for _ in 1...10 {
let dice1: Int = rollDice()
let dice2: Int = rollDice()
print("Without label >> dice1: \(dice1), dice2: \(dice2), therefore dice1 > dice2 is \(dice1 > dice2)")
switch true {
case dice1 > dice2: break
default: continue
}
}
Whitout label >> dice1: 1, dice2: 4, therefore dice1 > dice2 is false
Whitout label >> dice1: 2, dice2: 4, therefore dice1 > dice2 is false
Whitout label >> dice1: 3, dice2: 3, therefore dice1 > dice2 is false
Whitout label >> dice1: 1, dice2: 1, therefore dice1 > dice2 is false
Whitout label >> dice1: 3, dice2: 4, therefore dice1 > dice2 is false
Whitout label >> dice1: 4, dice2: 6, therefore dice1 > dice2 is false
Whitout label >> dice1: 6, dice2: 2, therefore dice1 > dice2 is true
Whitout label >> dice1: 3, dice2: 1, therefore dice1 > dice2 is true
Whitout label >> dice1: 6, dice2: 6, therefore dice1 > dice2 is false
Whitout label >> dice1: 3, dice2: 4, therefore dice1 > dice2 is false
break
μ μν΄ For-In Loops λ₯Ό μ’
λ£ν κ² κ°μ§λ§ switch ꡬ문 μμμ λ°μν break μ΄κΈ° λλ¬Έμ switch κ΅¬λ¬Έλ§ μ’
λ£ νλ€.
λ°λΌμ λ€μκ³Ό κ°μ΄ label
μ μ΄μ©νλ©΄ μ μ΄ λͺ
λ Ήμ μ νν 컨νΈλ‘€ ν μ μλ€.
gameLoop: while true {
let dice1: Int = rollDice()
let dice2: Int = rollDice()
print("With label >> dice1: \(dice1), dice2: \(dice2), therefore dice1 > dice2 is \(dice1 > dice2)")
switch true {
case dice1 > dice2: break gameLoop
default: continue
}
}
With label >> dice1: 2, dice2: 5, therefore dice1 > dice2 is false
With label >> dice1: 4, dice2: 1, therefore dice1 > dice2 is true
7. Early Exit
guard
λ if μ μ μ¬νμ§λ§ νμ else μ μ΄ λ€λ°λ₯΄λ©°, else clause λ λ°λμ return
, break
, continue
, throw
μ
κ°μ Control Transfer Statements
λ₯Ό μννκ±°λ fatalError(_:file:line:)
μ κ°μ΄ return
μ΄ μλ ν¨μλ λ©μλλ₯Ό νΈμΆν΄μΌνλ€.
μ Switch-True λ₯Ό μ¬μ©ν Validation Check,
Validation Check with Compound Cases guard
λ₯Ό μ΄μ©ν΄ λ€μ μ¨λ³΄μ.
struct User {
var name: String?
var age: Int?
var phone: String?
var height: Double?
var weight: Double?
}
func validateUser(of user: User?) -> Bool {
guard let user = user else { return false }
guard let age = user.age else { print("age is nil"); return false }
if (age < 0) || (age > 130) { print("invalid age"); return false }
guard let _ = user.name else { print("name is nil"); return false }
guard let _ = user.phone else { print("phone is nil"); return false }
guard let _ = user.height else { print("height is nil"); return false }
guard let _ = user.weight else { print("weight is nil"); return false }
return true
}
var myUser = User(name: "νκΈΈλ", age: 132, phone: "010-4434-3556", height: 183.2, weight: 74)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
invalid age
Validation check result of myUser is false.
var myUser = User(name: "μ₯λ³΄κ³ ", age: 42, phone: "010-2342-1234", height: 175.2, weight: nil)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
weight is nil
Validation check result of myUser is false.
var myUser = User(name: "μ΄μμ ", age: 30, phone: "010-7423-3464", height: 169.6, weight: 52)
let result: Bool? = validateUser(of: myUser)
print("Validation check result of myUser is \(result!).")
Validation check result of myUser is true.
Reference
- βControl Flow.β The Swift Programming Language Swift 5.7. accessed Oct. 11, 2022, Swift Docs Chapter 4 - Control Flow.