Patrick's 데이터 세상
Swift 반복문, 제어문 본문
반응형
SMALL
반복문
for
for-in
범위 연산자(c 스타일 for 대체)
for i in 0..<10{
print("For 반복문 \(i)")
}
Array, Set과 사용하기
for item in [1, 2, 3, 4, 5]{
print(item)
}
딕셔너리와 문자열 순회
딕셔너리 - 튜플
for (kor, eng) in dic1{
print("key : \(kor) Value : \(eng)")
}
문자열의 뷰(콜렉션)
for ch in str.characters{
print(ch)
}
while 반복문
while i < 10{
i += 1
}
repeat- while
repeat{
j += 1
if j > 10 { break }
} while true
if 조건문
조건부에 괄호 생략 가능
바디의 중괄호 생략 불가
조건절 : 결과가 Bool
nil 비교시 != nil, ==nil을 붙여야 함
if와 else
var bloodType = "C"
if bloodType == "A"{
print("혈액형은 A")
}
else if bloodType == "B" || bloodType == "O"{
print("B나 O형"
}
else{
print("그러면 AB형?")
}
if-let 바인딩
바인딩
유효한 값 판단(nil 여부)
if let val = someFunc(){
print("\(val)")
}
다중 바인딩
if let val1 = someFunc(),
let val2 = anotherFunc() {
print("val1, val2는 모두 유효한 값")
}
버전 체크 : #available(FLATFORM VERSION)
if #available(IOS 10, macOS 10.12, *){
// IOS 10 이상, macOS 10.12 이상
} else {
// IOS 10, macOS 10.12 이전 버전용 코드
}
Early Exit
함수와 반복문에서 Exit
guard
if 조건문과 유사한 사용
Early Exit 용으로 사용
바디에는 exit 명령 필수
if 문의 조건 ; 진행 불가능한 상황의 조건 작성
guard 문의 조건 : 진행 가능한 상황의 조건 작성
guard [조건] else {
// exit 명령 (return or break)
}
바인딩 스코프
func example() {
guard let val = someFunc() else {
// 스코프 // return, break 사용
}
print("val은 유효한 값 : \(val)") // 같은 레벨의 스코프 사용 가능
}
guard, if 차이
// guard
for item in array {
guard item > 0 else {
break
}
print(item)
}
// if
for item in array {
if item < 0 {
break
}
print(item)
}
switch
조건에 맞는 case 하나만 실행
break 불필요
fallthrough : 다음 case 실행
switch someValue {
case 1:
print("1")
case 2:
print("2")
default:
print("Other")
}
범위 연산자
switch someValue{
case 1, 2, 3:
print("1, 2 혹은 3")
fallthrough
case 4 ..<6:
print("4에서 5사이")
case 6:
print("Six")
default:
print("나머지")
}
튜플 , 언더스코어(_)
var tupleVal = (1, "One")
switch tupleVal {
case (0, "Zero"):
case (0, "영"):
print("0,영")
case (1, _): // _ 사용하지 않음
print("1, 일")
default:
print("Other")
}
밸류 바인딩
var point = (2, 2)
switch point {
case (1, let y): // 앞 자리가 맞으면 y로 상수 받음
print("1, \(y)")
case (let x, 2): // 뒷 자리가 맞으면 x로 상수 받음
print("\(x), 2")
case let(x, y):
print("\(x), \(y)")
}
바인딩과 조건 : where
switch point {
case let(x, y) where x>0:
print("x가 0보다 크다")
case let(x,y) where x<0 && y>0:
print("2사 분변")
defaultL
print("그 외")
}
출처 : t academy swift 강좌
반응형
LIST
'Programming > Swift' 카테고리의 다른 글
Swift 함수 (0) | 2020.06.23 |
---|---|
Swift nil, optional (0) | 2020.06.23 |
Swift 다수 데이터 처리 (0) | 2020.06.23 |
Swift 문자, 문자열 (0) | 2020.06.23 |
Swift 데이터 타입과 연산자 (0) | 2020.06.23 |
Comments