_Rey
프로그래뭄
_Rey
전체 방문자
오늘
어제
  • 분류 전체보기 (118)
    • Life (2)
    • iOS (49)
      • iOS (13)
      • Swift (19)
      • UIKit (0)
      • RxSwift (6)
      • SwiftUI (11)
    • Design Pattern (14)
      • GoF - Creational Patterns (6)
      • GoF - Structural Patterns (7)
    • Data Structure & Algorithm (48)
      • Data Structure (3)
      • Algorithm (8)
      • Advent of Code 2024 (1)
      • 코테 스터디 TIL (36)
    • English (2)
    • Book (2)
      • Clean Architecture (2)

블로그 메뉴

  • Instagram
  • Github
  • Naver Blog

공지사항

  • Hello, Programoom

인기 글

hELLO · Designed By 정상우.
_Rey

프로그래뭄

iOS/Swift

[Swift] Conditional & Loop

2022. 6. 5. 01:00

swift.org를 참고하여 정리한 글입니다.

 

Swift.org

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

www.swift.org

 

조건과 반복문에 대해서 알아보자.


if & else

let int3 = 3

if 5 > int3 {
    print("OK")
}

// if와 else
if 5 > int3 {
    print("OK")
} else {
    print("NO")
}

// else-if로 조건을 쓸 수 있다.
if 2 > int3 {
    print("if 2")
} else if 5 > int3{
    print("else if 2")
}

switch-case

let switchValue = 0
switch switchValue {
case ..<4 :
    print("switch case ..<4")
    fallthrough // 사용하면 조건과 상관없이 다음 case가 실행됩니다.
case 1,3,5,7,9 :
    print("switch case 1,3,5,7,9")
case 5... :
    print("switch case 5...")
case 0,2,4,6,8 :
    print("switch case 0,2,4,6,8")
default:
    print("switch default")
}

// switch case ..<4
// switch case 1,3,5,7,9

삼항연산자

// condition ? {true condition code} : {false condition code}

let int51 = 51
(100 > int51) ? print("100보다 작아요.") : print("100보다 같거나 커요.")
// "100보다 작아요."

for-in

for num in 0...4 {
    print(num)
}
// 0
// 1
// 2
// 3
// 4

let anyDictionary: [String: Any] = [ "dictionary" : [4:"four"],
                  "array": [1,2,3,4,5],
                   "int": 5 ]
for element in  anyDictionary {
    print(element)
}

// (key: "dictionary", value: [4: "four"])
// (key: "array", value: [1, 2, 3, 4, 5])
// (key: "int", value: 5)

while

var num = 3

// 조건 체크 -> 실행 -> 조건체크 ...
while num > 0 {
    print("while num: \(num)")
    num -= 1
}

// while num: 3
// while num: 2
// while num: 1

repeat-while

// 실행 -> 조건체크 -> 실행 ...
num = 0
repeat {
    print("repeat-while num: \(num)")
    num -= 1
} while num > 0

// repeat-while num: 0

break

for-in, while, repeat-while의 반복 루프 중 break를 통해 반복을 멈추고 코드블럭을 빠져나올 수 있다.

num = 1
while num > 0 {
    print("while num: \(num)")
    num += 1
    if num == 3 {
        print("break! \(num)")
        break
    }
}

// while num: 1
// while num: 2
// break! 3
저작자표시 비영리 변경금지 (새창열림)

'iOS > Swift' 카테고리의 다른 글

[Swift] Optional(옵셔널)  (0) 2022.06.09
[Swift] Function  (0) 2022.06.09
[Swift] Collection Type  (0) 2022.06.04
[Swift] 기본 데이터 타입  (0) 2022.06.04
[Swift] Protocol  (0) 2022.05.27
    'iOS/Swift' 카테고리의 다른 글
    • [Swift] Optional(옵셔널)
    • [Swift] Function
    • [Swift] Collection Type
    • [Swift] 기본 데이터 타입
    _Rey
    _Rey
    잘 배워서 다 남주자

    티스토리툴바