iOS 프로그래밍 실무 (5)

김제형·2025년 4월 17일

열거형

  • 관련있는 데이터들이 멤버로 구성되어 있는 자료형 객체
enum Compass {
    case North
    case South
    case East
    case West
//case는 처음만 쓰고 , 로 나열해도 된다.
}
//var x : Compass // Compass형 인스턴스 x
print(Compass.North) // North
var x = Compass.West
print(type(of:x)) // Compass
x = .East
// .만 있는 경우 열거형 이름 compass 를 생략한 것이다.
print(x) // East

//North
//Compass
//East
enum Compass {
    case North
    case South
    case East
    case West
}
var direction : Compass
direction = .South
switch direction {  //switch의 비교값이 열거형 Compass
case .North:    //direction이 .North이면"북" 출력
    print("북")
case .South:
    print("남")
case .East:
    print("동")
case .West:
    print("서") //모든 열거형 case를 포함하면 default 없어도 됨
}
// 남

열거형 rawvalue - Int

enum Color: Int { //원시값(rawValue) 지정
    case red
    case green = 2
    case blue
}
print(Color.red) //red
print(Color.blue)
print(Color.red.rawValue) //0
print(Color.blue.rawValue)

red
blue
0
3

열거형 rawvalue - String

enum Week: String {
    case Monday = "월"
    case Tuesday = "화"
    case Wednesday = "수"
    case Thursday = "목"
    case Friday = "금"
    case Saturday //값이 지정되지 않으면 case 이름이 할당됨
    case Sunday // = "Sunday"
}
print(Week.Monday) //Monday
print(Week.Monday.rawValue) //월
print(Week.Sunday)
print(Week.Sunday.rawValue)

//Monday
//월
//Sunday
//Sunday

연관 값(associated value)을 갖는enum

enum Date {
    case intDate(Int,Int,Int) //(int,Int,Int)형 연관값을 갖는 intDate
    case stringDate(String) //String형 연관값을 값는 stringDate
}
var todayDate = Date.intDate(2025,4,30)
todayDate = Date.stringDate("2025년 5월 20일") //주석처리하면? 2025년 4월 30일 < 이라는 값이 나옴
switch todayDate {
case .intDate(let year, let month, let day):
    print("\(year)\(month)\(day)일")
case .stringDate(let date):
    print(date)
}
//2025년 5월 20일

옵셔널 - 연관성을 가진 열거형

let age: Int? = 30 //Optional(30)
switch age {
case .none: // nil인 경우
    print("나이 정보가 없습니다.")
case .some(let a) where a < 20:
    print("\(a)살 미성년자입니다")
case .some(let a) where a < 71:
    print("\(a)살 성인입니다")
default:
    print("경로우대입니다")
} //30살 성인입니다.

클래스(class)와 구조체(structure)의 차이점

  • 클래스는 상속 받고 할 수 있고 구조체는 불가능하다.
  • 부모와 자식 관게에서는 형변환이 예외로 된다.

값타입 예시

var x = 1
var y = x
print(x,y)
x = 2
print(x,y)
y = 3
print(x,y)

//1 1
//2 1
//2 3

Value type VS Reference type

profile
개발자 지망생

0개의 댓글