iOS/Swift

[Swift] 조건문(Conditional), 반복문(Loop)

year.number 2022. 7. 26. 14:22

 

조건문

if - else 구문

 

- if 뒤에 소괄호는 생략 가능하지만, 중괄호는 생략 불가

- Swift의 조건에는 항상 Bool 타입이 와야 한다

 

switch 구문

 

- switch 사용 시에 반드시 default값이 존재해야 한다. 안 그러면 컴파일 에러!

  // ERROR: switch must be exhaustive

 

- break문이 명시하지 않아도 자동으로 설정되어 있음

   // 무시하는 방법: fallthrough

 

case 1..<100:       .. 온점 2개는 1이상 100미만

    print("1~99")

case 100:

    print("100")

case 101...Int.max:  ...온점 3개는 1이상 max이하

    print("over 100")

 

 

소스코드

//
//  Conditional.swift
//  iOS study
//
//  Created by yeonsu on 2022/07/26.
//

import Swift

let someInteger = 100

// ================== < if - else 구문 > ==================

if someInteger < 100 {  //if 뒤에 소괄호는 생략 가능하지만, 중괄호는 생략 불가
    print ("100 미만")
} else if someInteger > 100 {
    print ("100 초과")
} else {
    print ("100")
}   //100 출력

// Swift의 조건에는 항상 Bool 타입이 와야 한다
// Ex) someInteget는 Int 타입이기 때문에 if문의 조건문에 쓸 시 컴파일 오류 발생!
// if someInteger {}    //컴파일 에러



// ================== < 범위 연산자 Switch > ==================
// switch 사용 시에 반드시 default값이 존재해야 한다. 안 그러면 컴파일 에러!
// ERROR: switch must be exhaustive

// break문이 명시하지 않아도 자동으로 설정되어 있음
// 무시하는 방법: fallthrough


switch someInteger {
case 0:
    print("zero")
case 1..<100:       //1이상 100미만
    print("1~99")
case 100:
    print("100")
case 101...Int.max:
    print("over 100")
    
default:
    print("Unknown")
}   //100 출력


// 정수 외에도 대부분의 기본 타입을 사용할 수 있다
switch "yeonsu" {
case "jenny":
    print("jenny")
case "mina":
    print("mina")
case "jobs":
    print("jobs")
    
default:
    print("Unknown")
}

 

출력결과

 


반복문

for - in 구문
/*
 for 임시상수 in 시퀀스아이템 {
    실행코드
 }
 */

for i in integers {
    print(i)
}

 

Dictionary의 item은 key와 value로 구성된 튜플 타입이다
for (name, age) in people {

    print ("\(name): \(age)")

}

 

튜플 타입이란?

- 다양한 값(데이터)들의 묶음(배열과의 차이점 존재O, 튜플은 데이터 타입이 같을 필요가 없음)

var 변수명: (데이터 타입1, 데이터 타입2) = ( 값1 , 값2)   //괄호 안에 원하는 값 나열
var 변수명 = (값1, 값2)   //Swift가 알아서 타입 적용
let yeonsu = ("Kim", 24)

 

- 튜플은 선언할 때 배열과 같이 index를 가진다

- 튜플을 선언한 뒤에 자료형/멤버의 개수를 변경할 수 없다

 

 

튜플 값에 접근하는 방법

.(dot)
yeonsu.0   //Kim
yeonsu.1   //24

 

튜플 네임

let yeonsu = (name: "yeonsu", age: 26)

이름을 설정하면 index가 아닌 지정한 이름으로 접근이 가능하다

 

 

튜플 값 분해하기

튜플의 멤버를 각각 상수에 저장하고 싶을 때

var yeonsu = (name: "yeonsu", age: 24)

let name = yeonsu.name
let age = yeonsu.age


===== < decomposition 문법 > =====
let (name, age) = yeonsu

===== < wildcard pattern > =====
// 필요없는 멤버 생략하고 바인딩 가능
let(name, _) = yeonsu   //기존에는 튜플의 개수 = 상수의 개수여야 함

 

🔗 https://babbab2.tistory.com/31 게시글을 참고했습니다.

 


while / repeat - while 문

Swift에서 do - while 을 쓰지 않는 이유는 do가 에러를 표시할 때 사용하기 때문이라고 한다

 

 

 

소스코드

//
//  loop.swift
//  iOS study
//
//  Created by yeonsu on 2022/07/26.
//

import Swift

var integers = [1, 2, 3]
let people = ["yeonsu": 24, "John": 25, "Mike": 23]

// ================= < for - in > 구문 =================

/*
 for 임시상수 in 시퀀스아이템 {
    실행코드
 }
 */

for i in integers {
    print(i)
}


// Dictionary의 item은 key와 value로 구성된 튜플 타입이다
for (name, age) in people {
    print ("\(name): \(age)")
}


// ================= < While > 구문 =================

while integers.count > 3 {  //조건 숫자에 따라 달라지는 거 뭐지..?
    integers.removeLast()
}

print(integers)



// ================= < repeat - while > 구문 =================

repeat {
    integers.removeLast()
} while integers.count > 0

print(integers)

 

실행결과