본문 바로가기
🍎iOS프로그래밍/오늘의 공부

Swift의 반복문,제어문(if문, for문, repeat-whlie문 ,guard문, switch-case문) / iOS프로그래밍

by 둥둥동동# 2021. 9. 26.
728x90

 

 

제어문 

 

Swift의 다양한 제어문, 반복문에 대해 알아보겠습니다

 

 

 

for in문

 

숫자 범위, 배열, 문자열을 순서대로 순회합니다

 

for반복시킬 변수 하나와 순회할 범위를 지정하여 사용합니다

for i in 1...3{
    print(i)
}
//1
//2
//3
cs

 

let Fruit = ["Apple""Banana""Kiwi""Grape"]
for name in Fruit {
    print("I'm \(name)")
}
//I'm Apple
//I'm Banana
//I'm Kiwi
//I'm Grape
cs

 

 

 

if문

 

다음과 같이 사용합니다

let myNum = 5
if myNum == 1 {
    print("1")
}else if myNum == 2{
    print("2")
}else{
    print("else")
}
//else
cs

※Swift에서 if문을 단 한줄만 작성하더라도 꼭 {}를 붙여야 합니다

 

번외)if  let문

if let문으로 옵셔널 바인딩된 상수를 if문 안에서 사용할 수 있습니다

옵셔널의 자세한 포스팅은 여기->클릭

 

 

switch case문

 

let myNum = 1
switch myNum{
    case 1,3,5,7,9:
        print("odd")
    case 2,4,6,8:
        print("even")
    default:
        print("wrong number")
}
//odd
cs

No Implicit Fallthrough

C나 Object-c같은 경우 break문을 명시했어야 했지만 Swift에서는 break문이 생략되어 있습니다

해당 case의 실행구문이 모두 실행되면 자동으로 switch블럭을 빠져나오게 됩니다

 

만약 case문을 아래로 한번 더 진행하고자 한다면 fallthrough를 사용하면 됩니다

let myNum = 1
switch myNum{
    case 1,3,5,7,9:
        print("odd")
        fallthrough
    case 2,4,6,8:
        print("even")
    default:
        print("wrong number")
}
//odd
//even
cs

 

조건의 범위를 지정하거나 콤마(,)로 조건을 여러개 지정할 수 있습니다

let myNum = 10
switch myNum{
    case 0:
        print("0")
    case 1..<9:
        print("1~9")
    case 10,11,12:
        print("10,11,12")
    default:
        print("over 12")
}
 
cs

 

Value Binding

변수의 값도 바인딩을 할 수 있습니다

let anotherPoint = (20)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
cs

anotherPonin 튜플의 값은 (2, 0)입니다 

첫번째 case문에서 첫번째 값을 x로 두고 두번째값이 0일 때를 조건으로 걸었습니다

anotherPonin 튜플의 두번째 값이 0이라 참이 되어 해당 case문이 실행됩니다

case 조건에서 선언된 x를 통해 anotherPonin 튜플의 첫번째 값을 이용할 수 있습니다

 

where절

 

witch-case문에도 where사용이 가능합니다 

var size:Int = 90 
 
switch (size){
    
    case 90...100 where size % 5 == 0:
        print("in stock")//in stock
    case 105 :
        print("sold out")
        
    default:
        print("wrong size")
}
 
cs

90~100사이의 숫자이면서 5로나누어지는 숫자를 조건으로 걸었습니다

 

 

 

guard문

 

if문은 조건이 참이었을 때 실행되지만 guard문은 조건이 거짓일 때 실행됩니다

이 성질을 이용해 함수, 조건문의 조기탈출(Early Exit)를 위해 사용됩니다

return, break와 같은 블럭을 종료시키는 구문이 필수로 들어가야 합니다

func greet(person: [StringString]) {
    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."
cs

 

파라미터로 "name"나 "location"태그의 값이 들어오지 않으면 함수를 종료시키는 코드입니다

 

 

 

while repeat-while문

 

Swift에는 while문과 repeat-wile문이 있습니다

 

whlie문은 조건문이 참이 될 때 까지 반복합니다

var num = 0
whlie(num == 3){
    num +=1
}
print(num)
//3
cs

 

repeat-while문은 실행구문을 먼저 실행한 뒤 조건을 체크합니다

do-while과 동일한 기능을 합니다

var num = 0
repeat{
    num += 1
}while num == 0 
print(num)
//1
cs

 

 

 

 

참고 서적

 

iOS프로그래밍기초(21-2학기)한성현교수님 강의 내용

Swift 문서 참조

https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

 

728x90
반응형

댓글