개발 일기

Control Flow ? 본문

컴퓨터 언어/swift

Control Flow ?

이건욱

For In Loop

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

다음과 같이 Array에 대해서 마지막까지 반복해서 값을 가져옵니다.

아래와 같이 Dictionary와 Tuple에 대해서도 가능합니다. (다만 Dictionary는 순서를 보장하지 않습니다.)

 

Collection Type에 대한 자세한 내용은 링크를 걸어드리겠습니다.

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

 

숫자범위로 for In을 하고 싶은 경우에는 다음과 같이 할수가 있습니다.

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)")
// Prints "3 to the power of 10 is 59049"

 

다음과 같이 마지막값을 포함을 안하고 싶은 경우에는 '<' 기호를 사용하면 됩니다.

let minutes = 3
for tickMark in 0..<minutes {
    print(tickMark)
}

 

일정한 간격으로 반복을 하고 싶은 경우에는  stride(from:to: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)
}
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 Loop 

While Loop는 condition 값이 False가 될 때 까지 반복합니다.

while condition {
    statements
}

 

Repeat-While

Repeat-While문은 repeat에 있는 값을 먼저 실행 한뒤에 condition에 따라서 다음에 다시 반복할지 여부를 결정합니다.

다른 언어에서는 do-while가 비슷 합니다.

repeat {
    statements
} while condition

 

IF

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."

 

조건에 실패한 경우에는 다음과 같이 else 문에 대한 내용을 실행합니다.

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."

N개의 조건에 대해서 하고 싶은 경우에는 다음과 같이 할수가 있습니다.

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."

 

Switch

Switch문은 조건이 일치하는 첫번째 내용을 실행합니다.

 

case을 통해서 조건을 설정하고 조건이 다 실패할 경우에 default을 호출하게 됩니다.

둘 이상의 case를 실행하지 않기 때문에 JAVA or C 와 같이 break문이 필요하지 않습니다. 

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

 

다중으로 조건을 설정하고 싶은경우에는 다음과 같이 할수가 있습니다.

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

 

 

[다양한 사용 예시]

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).")
// Prints "There are dozens of moons orbiting Saturn."
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"
 let anotherPoint = (2, 2)
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))")
}

 

switch문 같은 경우에는 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"

 

swift에서는 기본적으로 아래에 케이스를 넘어가지 않습니다.

하지만 다음과 같은 fallthrough 키워드로 넘어갈수가 있습니다.

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."

 

다음과 같이 중첩 루프가 있을 때 구별을 더 편리하기 하기 위해서 label을 지정할수가 있습니다.

주로 break , continue 와 같이 사용을 합니다.

label name: while condition {
    statements
}
gameLoop: while square != finalSquare {
    diceRoll += 1
    if diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        // diceRoll will move us to the final square, so the game is over
        break gameLoop
    case let newSquare where newSquare > finalSquare:
        // diceRoll will move us beyond the final square, so roll again
        continue gameLoop
    default:
        // this is a valid move, so find out its effect
        square += diceRoll
        square += board[square]
    }
}
print("Game over!")

 

그 다음으로 guard let 에 대해서 살펴보도록 하겠습니다.

guard let은 조건이 참이면 다음에 있는 코드를 실행 합니다.

 

보통은 optional과 함께 사용이 됩니다. 따라서 optional 값이 nil일때 보통 return, break, continue, or throw

와 같이 사용이 됩니다.

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."

 

마지막으로 API 사용할때 버전 체크를 사용할 때 다음과 같이 가능합니다.

if #available(iOS 10, macOS 10.12, *) {
    // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
    // Fall back to earlier iOS and macOS APIs
}

'컴퓨터 언어 > swift' 카테고리의 다른 글

Closures ?  (0) 2020.05.17
Function ?  (0) 2020.05.16
Collection Type ?  (0) 2020.05.03
Strings and Characters  (0) 2020.05.01
기본적입 타입 소개 ?  (0) 2020.04.25
Comments