Link
Notice
HIT해
[Swift 기초문법 - 50] 자료형 체크 본문
728x90
Swift에서 자료형을 체크하는 방법을 알아보려한다.
- if is
- guard is
- switch case is
- if case is
- guard case is
if is
class Cat {}
class Dog {}
let myCat = Cat()
if myCat is Cat {
print("고양이입니다")
}
guard is
func checkIfIsCat(){
guard myCat is Dog else {
print("고양이가 아닙니다")
return
}
print("고양이입니다.")
}
checkIfIsCat() // 고양이가 아닙니다
switch case is
switch myCat {
case is Dog:
print("강아지입니다.")
// 자료형 명을 변경해서 확인해볼 수 있다.
case let mykitty as Cat :
print("고양이 입니다")
}
// 고양이 입니다.
if case is
// 자료형이 먼저 나온다
if case is Cat = myCat {
print("고양이 입니다")
}
case is 구문은 자료형이 먼저 나온다
guard case is
func checkIsDog(){
guard case is Cat = myCat else {
print("강아지가 아닙니다")
return
}
print("고양이입니다.")
}
checkIsDog() // 고양이입니다.
'Swift > 기초문법' 카테고리의 다른 글
[Swift 기초문법 - 52] Optional Protocol (0) | 2024.08.19 |
---|---|
[Swift 기초문법 - 51] 중첩 타입 Nested Type (0) | 2024.08.19 |
[Swift 기초문법 - 49] 프로토콜 조건 적용 (1) | 2024.08.19 |
[Swift 기초문법 - 48] Toggle (0) | 2024.08.19 |
[Swift 기초문법 - 47] Singleton 패턴 (0) | 2024.08.19 |