본문 바로가기
실무 (iOS)

iOS 프로그래밍 실무 (7주차) [ 클래스 , 구조체 , 열거형 ]

by DeathStar183 2025. 4. 19.

-이번주에 보고 넘어갈것들

 

- 열거형

- 구조체

- 클래스

 

 

 

1. 열거형 (enum)

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/enumerations/

 

Documentation

 

docs.swift.org

 

 

 

 

1-1. 열거형 정의

 

 

 

 

Windows에서 swift 언어 사용하기 ↓

https://www.onlinegdb.com/online_swift_compiler

 

Online Swift Compiler - online editor

OnlineGDB is online IDE with swift compiler. Quick and easy way to run swift scripts online.

www.onlinegdb.com

 

 

 

1-2. 열거형 멤버별 기능 정의

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 없어도 됨
}

 

 

 

1-3. 열거형 멤버에 메서드 넣기

enum Week {
	case Mon,Tue,Wed,Thur,Fri,Sat,Sun
	func printWeek() { //메서드도 가능
		switch self {
		case .Mon, .Tue, .Wed, .Thur, .Fri:
			print("주중")
		case .Sat, .Sun:
			print("주말")
		}
	}
}
Week.Sun.printWeek() //Sun이므로 주말이라고 뜨며, Mon,Tue같은건 주중으로 나옴

 

 

 

1-4. 열거형의 raw Value값(원시값)

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) // 3

// 기본적으로는 색깔 이름을 출력하지만,
// Int를 붙이면 (Int형)숫자로도 사용하겠다는 이야기가 됨

 

 

 

1-5. String형 값을 가진 열거형의 raw Value

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) //Sunday
print(Week.Sunday.rawValue) //Sunday

// 기본적으로 rawValue가 있다면 그걸 불러오지만, 없다면 case의 이름이 대신 할당받아서 불러와짐

 

 

 

1-6. 연관 값(Associated Value)을 가지는 enum

 

enum Date { //1.
	case intDate(Int,Int,Int) //(int,Int,Int)형 연관값을 갖는 intDate
	case stringDate(String) //String형 연관값을 값는 stringDate
}

var todayDate = Date.intDate(2025,4,30) //착각하기 쉬우므로 주의 2.
todayDate = Date.stringDate("2025년 5월 20일") // 3.
// 4-2. 주석처리 했다면? 

switch todayDate {
	case .intDate(let year, let month, let day):
		print("\(year)년 \(month)월 \(day)일")
	case .stringDate(let date):
		print(date)
} //4-1.

번호 순서대로 설명드리겠습니다.

1. Int형 3개의 연관값을 가지는 intDate가 형성되고, 그 다음에는 string형 연관값을 갖는 stringDate가 생성됩니다.

2. 변수 todaydate를 만들고, intDate에 2025 , 4 , 30의 Int형 정수를 넣어서 todaydate에 할당을 시켜줍니다.

3. 하지만, 다음에 바로 stringDate가 string형 값을 넣으라고 했으므로 할당된 Int값이 자동으로 사라집니다. 

4-1. 밑의 switch문에서 결국 stringDate문에 부합하므로 string형 값인 2025년 5월 20일이 나옵니다.

4-2. 주석처리시, Int형 값을 가지고가서 switch문에서 intDate에 부합하므로 2025년 4월 30일이 나옵니다.

 

 

 

1-7. 옵셔널도 연관값을 가짐

 

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살 성인입니다

 

 

 

2. 구조체 ( struct )

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes/

https://developer.apple.com/documentation/swift/array

 

 

 

2-1. 구조체는 Memberwise initializer 자동 생성

 

struct Resolution { //구조체 정의
	var width = 1024 //프로퍼티
	var height = 768
}
let myComputer = Resolution() //인스턴스 생성
print(myComputer.width) //프로퍼티 접근

struct Resolution { //구조체 정의
	var width : Int //프로퍼티 초기값이 없어요!!
	var height : Int
} 
//init()메서드 없어요!, 그런데도 작동?
let myComputer = Resolution(width:1920,height:1080) //Memberwise Initializer
print(myComputer.width)

//class인 경우
class Resolution { //class
	var width : Int 
	var height : Int
    init(width : Int, height : Int)
    { 
    self.width = width 
    self.height = height    
    }
} 
let myComputer = Resolution(width:1000,height:2000)
print(myComputer.width)

 

 

 

2-2. 클래스 안에 구조체 넣기

struct Resolution { //구조체는 기본적으로 public임
	var width = 1024
	var height = 768
}
class VideoMode {
	var resolution = Resolution() //구조체의 모든정보를 클래스내 변수에 저장
	var frameRate = 0.0
}
let myVideo = VideoMode() //클래스내의 모든정보를 상수 myVideo에 저장, 구조체 정보도 가지고 있음
print(myVideo.resolution.width) //클래스의 변수 resolution에 저장된 구조체 값 (width)을 불러옴

 

 

 

TMI : swift 기본 데이터 타입은 모두 구조체에 해당

 

 

 

2-3-1. 클래스 (class) 와 구조체 (struct) 의 공통점?

 

 

 

2-3-2. 하지만 클래스는 구조체보다 좀더 많은 특징을 가짐

 

 

 

2-4. 구조체는 값이 다르지만, 클래스는 같게 나온다?

struct Human {
	var age : Int = 1
}
var kim = Human()
var lee = kim //값 타입 1.
print(kim.age, lee.age)
lee.age = 20
print(kim.age, lee.age) //2.
kim.age = 30
print(kim.age, lee.age)
// 1 1
// 1 20
// 30 20
class Human {
	var age : Int = 1
}
var kim = Human()
var lee = kim //참조 타입 3.
print(kim.age, lee.age)
lee.age = 20
print(kim.age, lee.age) // 4.
kim.age = 30
print(kim.age, lee.age)
// 1 1
// 20 20
// 30 30

이것도 번호 순서대로 설명드리겠습니다.

1. 변수 kim에 구조체의 정보를 넣고, 변수 kim은 변수 lee에게 자신의 값을 복사 시켜줍니다. (출력시 둘다 1 , 1 이 나옵니다.)

2. 근데 lee에게 20이라는 새로운값을 지정하고 출력하면 20 , 20이 아닌 20 , 1이 나옵니다.

    이러한 이유는, 값을 복사할때 새로운 데이터를 만들어 저장하는 방식이라, 원래있던 다른곳에 공유되지 않습니다.

 

3. 1번과 비슷하여서 생략

4. 여기가 크게 다른데, 앞서 구조체는 서로가 하나의 값 타입을 가져서 서로 공유가 되지 않는 반면에,

    반대로 클래스는 값을 공유하는게 아닌, 자신의 주소를 복사해주기에 구조체와 달리 값이 둘이 똑같이 나옵니다.

    ( 값의 주소를 복사해서 보냄 > 주소를 찾아감 > 주소값을 참조하여 값을 불러옴 > 주소값에서 불러오니 값도 동일함 )

 

 

 

2-5. 그렇다면 클래스와 구조체를 어느때에 사용해야 할까?

 

 

 

extra.  chatGPT의 답변

 

댓글