[Swift] 5. Control Flow

도윤·2021년 7월 14일
0

Swift

목록 보기
5/21

swift는 while,if,gaurd,switch,continue,break같은 흐름제어문을 제공.

Array,Dictionary,Sets를 쉽게 조회할 수 있는 for-in loop 제공.

복잡한 matching은 where을 통해 표현될 수 있다.

For-In Loops

let names = ["Anna", "Alex", "Brian", "Jack"] 
for name in names { 
	print("Hello, \(name)!") 
} 
// Hello, Anna! 
// Hello, Alex! 
// Hello, Brian! 
// Hello, Jack!

Dictionary에서는 (key,value)쌍으로 접근 가능.

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs

만약 sequense의 value가 필요없으면 _를 대신 써서 사용 가능.

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// Prints "3 to the power of 10 is 59049

for-in loops에서 stride(from:to:by)를 사용하면 from에서 to까지의 open구간을 by로 일정하게 설정할 수 있다.

let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}

close구간을 포현한다면 stride(from:throught:by)을 사용.

let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
    // render the tick mark every 3 hours (3, 6, 9, 12)
}

While

while문은 조건이 false가 될때까지 반복 실행되는 반복문.
반복문이 몇번 실행되어져야 할지 확실치 않을 때 사용하는것이 좋다.

while

시작부터 조건이 true인 경우에만 실행된다.

while condition {
    statements
}

Repeat While

처음 while문 실행 시 조건을 확인하지않고 무조건 실행하고 그 이후부터 조건 확인.
다른 언어의 Do-while문과 동일하다

repeat {
    statements
} while condition

Conditional Statements

원하는 상황에만 실행되도록 하는 조건문이다.
swift는 두가지 제공

  • if : 간단한 조건
  • switch : 복잡하고 여러개의 조건.

If

설정한 조건이 true이면 해당하는 코드 실행

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
}
// Prints "It's very cold. Consider wearing a scarf."

위 코드에서 조건이 true이므로 print가 실행된다. false라면 print되지 않는다.

temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's not that cold. Wear a t-shirt.

else와도 함께 사용할 수 있다. 조건이 False라면 else에 해당하는 코드가 실행된다. 둘중 하나의 코드는 무조건 실행된다.

temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen.

else if문을 추가하여 하나의 조건을 더 확인이 가능하다.

Switch

여러가지의 조건을 설정하여 가장 먼저 true가 되는 조건을 실행한다.

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
}

some value to consider : 조건들이 확인될 값
value가 1이면 response to value이고, 2이거나 3이면 respond to value2 or 3이다.
else문처럼 위 조건이 모두 아니면 default가 실행된다.

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")
}
// Prints "The last letter of the alphabet

No implict Fallthrough

c나 object-c와는 다르게 case에 break문을 적지 않아도 조건이 실행된 후 탈출된다. 두개의 조건이 실행되는 것 방지.

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// This will report a compile-time error

case "a"의 실행문이 적혀있지 않으므로 error발생

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// Prints "The letter A"

하나의 case에 or연산자처럼 둘중 하나의 조건만 맞아도 실행되도록 할 수 있다.

Interval Matching

case에 구간을 설정할 수도 있다.

let approximateCount = 62
let countedThings = "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).")

Tuples

같은 조건에서 여러값들을 확인하려면 Tuple을 사용하면 된다.
tuple의 값들은 다른 조건에 의해서 테스트될 수 있다.
tuple에 _을 사용한다면 어떠한 값을 넣어도 조건에 만족한다는 뜻이다.

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"

Value Binding

switch에 let이나 var로 변수 선언 가능.

let anotherPoint = (2, 0)
switch anotherPoint {
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))")
}
// Prints "on the x-axis with an x value of 2’

마지막 case는 어떠한 값을 넣어도 실행되는 조건이므로 default대신 사용 가능.

Where

추가조건 확인 가능

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
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")
}
// Prints "(1, -1) is on the line x == -y

Compound Cases

','을 사용하여 or연산자처럼 사용할 수 있다.

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) isn't a vowel or a consonant")
}
// Prints "e is a vowel

Compound Cases에 value binding도 가능.

let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
    print("On an axis, \(distance) from the origin")
default:
    print("Not on an axis")
}
// Prints "On an axis, 9 from the origin

Control Transfer Statements

실행 순서를 제어하는 코드로 continue,break,fallthrough,return,throw가 있다.

continue

해당 지점에서 작업을 중단하고 다음 반복을 시행하라는 명령문

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)
// Prints "grtmndsthnklk

Break

반복문에서 사용된다면 반복문이 종료될때까지 실행되는것이 아니라 즉시 종료하도록 함.

switch문에서 사용된다면 switch문이 즉시 종료.

let numberSymbol: Character = "三"  // Chinese symbol for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
    possibleIntegerValue = 1
case "2", "٢", "二", "๒":
    possibleIntegerValue = 2
case "3", "٣", "三", "๓":
    possibleIntegerValue = 3
case "4", "٤", "四", "๔":
    possibleIntegerValue = 4
default:
    break
}
if let integerValue = possibleIntegerValue {
    print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    print("An integer value couldn't be found for \(numberSymbol).")
}
// Prints "The integer value of 三 is 3.

Fallthrough

switch문에서 fallthrough을 사용한다면 c에서 break를 설정하지 않았을 때 처럼 아래의 조건문을 또 실행하게 된다.

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)
// Prints "The number 5 is a prime number, and also an integer.

Labeled statements

다른 반복문과 조건문 안에 또 다른 반복문과 조건문을 중첩하여 복잡한 제어 흐름 구조를 만들 수 있다.

이렇게 만든 루프와 조건문은 break를 사용해서 조기에 종료할 수 있다. 마찬가지로 continue문도 어떤 루프에 적용되는 것인지 명시하는것이 유용하다. 이러한 방법을 사용하기 위해 명령문 레이블을 사용하여 루프와 조건문을 표시할 수 있다. 명령문 레이블은 해당 루프 혹은 조건문 앞에 명시해 주면 된다.

label name: while condition {
    statements
}

Early Exit

if처럼 조건문의 값이 bool으로 나타나는것에 의존.
guard문은 조건이 true일때 gaurd문 } 이후의 코드를 실행한다.
if와 다르게 항상 Else와 같이 쓰이며 false인 경우 실행된다.

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }

    print("Hello \(name)!")

    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }

    print("I hope the weather is nice in \(location).")
}

greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino.

guard의 else부분에서 코드를 종료하기 위해서 break,continue,return,throw,fatalError등을 실해해야 한다.

0개의 댓글