2023. 7. 12. 00:55ㆍiOS 개발/SwiftUI
SwiftUI에서 데이터를 JSON형식으로 변환하려면 Codable프로토콜을 채택해야 한다.
import Foundation
import SwiftUI
struct Sticker: Codable, Identifiable {
var id: UUID = UUID()
var memo: String
var color: Color // <- 이놈 때문에 안됨
var date: Date
var dateString: String {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd EEEE HH:mm"
return dateFormatter.string(from: date)
}
}
하지만 위에서 Color 데이터타입은 Codable프로토콜에 맞지 않기 때문에 에러가뜬다.
Codable은 Decodable과 Encodable 프로토콜로 이루어진 typealiars(별명)인데
Decodable과 Encodable의 "Conforming Types(=적합한 타입)"에는 Color타입이 없다.
그래서 color를 연산프로퍼티로 만들어 해결할 수 있다.
Why?💡
연산 프로퍼티로 만든 color 값을 Codable에 포함할 수 있는 이유는 연산 프로퍼티가 실제 값을 저장하는 것이 아니라 계산에 의해 값을 반환하기 때문입니다.
Codable은 실제 값을 저장하는 프로퍼티만 인식하므로, 연산 프로퍼티는 직접 Codable을 준수할 필요가 없습니다.
즉, 연산 프로퍼티는 값을 직접 저장하지 않지만, 코드를 통해 값을 계산하고 반환하므로 이를 활용하여 값을 Codable에 포함시킬 수 있게 됩니다.
1. 먼저 colorIndex : Int 를 만들자
var colorIndex: Int = 0
2. color의 get 연산 프로퍼티를 만들어서 colorIndex의 값을 swich문에 넣은 뒤 color값이 나오게 하자
var color: Color {
get {
switch colorIndex {
case 0:
return .cyan
case 1:
return .purple
case 2:
return .blue
case 3:
return .yellow
case 4:
return .brown
default:
return .white
}
}
}
3. color의 set 연산 프로퍼티를 만들어서 받아온 color값을 swich문에 넣은 뒤 colorIndex에 저장하자
-> set에 newValue(받아온 color값)
var color: Color {
get {
switch colorIndex {
case 0:
return .cyan
case 1:
return .purple
case 2:
return .blue
case 3:
return .yellow
case 4:
return .brown
default:
return .white
}
}
set { // set으로 colorIndex에 저장
switch newValue { // newValue(받아온 color값)
case .cyan:
colorIndex = 0
case .purple:
colorIndex = 1
case .blue:
colorIndex = 2
case .yellow:
colorIndex = 3
case .brown:
colorIndex = 4
default:
colorIndex = 5
}
}
}
(연산프로퍼티는 set은 생략가능하지만 get은 생략할수 없어서 get먼저 생각하거나 동시에 생각하자.)
3. 그럼 이제 JSON형식으로 encode할때 color값이 들어가진다.
4. 다시 JSON형식을 decode하면 값이 그대로 가져와진다.
5. 이제 코드에 color값을 불러오면 color의 get 연산 프로퍼티가 실행되어 colorIndex 값에 맞는 color 값을 쓸 수 있다.
'iOS 개발 > SwiftUI' 카테고리의 다른 글
[TIL] 포도맛(스레드) 에러 (1) | 2024.03.16 |
---|---|
[ActionSheet] title 안나오게 할 수 있을까? (0) | 2023.07.31 |
[Clone App] Login - SwiftUI (#1) (0) | 2023.07.06 |
[SwiftUI] VStack (0) | 2023.06.19 |