🔎 1 . if 구문
- condition == 조건 == boolean
- 조건식의 결과가 true일 때만 코드 블록 내부의 구문 실행
- false이면 코드블록을 빠져나가 if블록 다음에 위치한 코드 수행
✅ if ~ else
- if 조건식 { 조건이 true 일 때 실행할 구문 }
- else { 조건이 false 일 때 실행할 구문 }
✅ if ~ else if
비교할 조건이 여러 개 있을 경우
if문은 위에서 아래로 조건을 평가하기 때문에 순서가 중요하다.
그래서 항상 까다로운 조건문이 먼저 오고 느순한 조건문이 나중에 와야 한다.
✅ #available 구문
OS 버전에 따라 기능이 다르게 제공 되어 OS 버전에 따라 구문을 나눠 작성할 필요가 있다.
특정 API를 사용할 때는 사용 가능한 iOS 버전과 기기를 체크해야 하는데 코드상에서 처리할 수 있는 구문
🔎 2. guard 구문
- if 구문과의 차이점
- else 블록이 필수
- 표현식의 결과가 true 일 때 실행되는 블록이 없음
- if 구문의 단점
조건이 여러 개일 때 if문 안에 if문이 계속 생겨 가독성이 좋지 않음 -> guard 구문의 필요성!!
- if구문와 유사하지만 else인 조건을 먼저 확인하려는 용도가 guard 구문이다!!!
-> early exit 하기 위한 목적
-> 조건을 만족한다면 다음 줄의 코드를 실행한다.
- guard 문은 조건이 true면 guard 구문을 끝내고 뒤에 이어지는 문장을 실행한다.
- false면 else문을 실행한다. if문과는 달리 else 부분은 생략할 수 없다.
- guard의 else 블록은 반드시 guard가 호출된 스코프를 종료 해야한다.
-> 함수에서는 return/ throw
반복문에서는 break/ continue이용.
반복문 안에 guard 구문이 중첩되어 있고 break를 만난다면 반복문 종료 - 조건이 많아져도 중첩이 발생하지 않아 가독성이 높다.
🔎 3. switch 구문
: 나열된 값을 순서대로 비교한 다음에 값이 일치하는 첫번째 패턴의 코드블록을 실행하는 문장
- 비교할 대상과 case 뒤의 값이 같다면 해당 case의 코드블럭이 실행된다.
실행 후 나머지 case에 대한 비교 없이 바로 switch 구문 종료 - 일치하는 case가 여러 개 있더라도 맨 처음에 일치한 case 구문 하나만 실행하고 나머지들은 비교 x
- 두번째 케이스처럼 매칭시킬 패턴을 두개 이상 나열시킬 수도 있다. (or)
- default에 항상 한줄 이상의 코드가 필요한데, 없다면 break를 사용한다.
- 처음부터 값을 하나씩 매칭하고 값이 같은 case 블록을 실행하고 다음 case는 확인하지 않고 바로 끝난다.
✅ fallthrough
- fallthrough를 사용하면 바로 다음 case의 문장이 실행된다.
- fallthrough에 의해 실행 흐름을 전달 받는 case 블록은 일치 여부와 상관 없이 코드 실행 후 switch 구문 종료.
- 구현에 따라서 버그가 발생할 수 있기 때문에 반드시 필요할 때만 사용하는 것이 좋다.
✅ switch ~ where
🔗 Reference
- 스파르타코딩 내일배움캠프 Swift 학습자료
'🍎 iOS > Swift' 카테고리의 다른 글
[ Swift 기초 문법 ] 옵셔널 타입(Optional Types) / Unwrapping / 옵셔널 바인딩(Optional Binding) (0) | 2024.05.02 |
---|---|
[ Swift 기초 문법 ] 제어 전달문 - break, continue, return, fallthrough / throw (0) | 2024.05.02 |
[ Swift 기초 문법 ] 반복문 - for문, while문 (0) | 2024.04.29 |
[ Swift 기초 문법 ] 자료형(데이터 타입, Data Type) / \() (0) | 2024.04.29 |
[ Swift 기초 문법 ] Global Scope / Local Scope / Declaration Scope (0) | 2024.04.25 |