CodabelModel -> DTOModel을 변환하는 과정에서 CodableModel에 들어가지만, 서버와 통신하는 과정에서 필요없는 프로퍼티가 Codable이 되지 않도록 하고 싶었다.
Firebase는 이게 문제다 ㄹㅇ 그냥 서버였으면 서버 측에서 안받으면 그만인데...
Encode, Decode하는 과정에서 무조건 nil을 보낼거기 때문에 무조건 옵셔널 프로퍼티만 가능하도록, 프로퍼티 래퍼를 작성해본다.
@propertyWrapper
struct BlockCodable<T: Codable> where T: ExpressibleByNilLiteral {
var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
extension BlockCodable: Codable {
init(from decoder: Decoder) throws {
self.wrappedValue = nil
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
이러쿵 해버리면
struct TestModel: Codable {
@BlockCodable var value: String?
var name: String
}
struct ContentView: View {
@State private var testModel = TestModel(value: "Hello", name: "World")
var body: some View {
VStack {
Text(String(
data: try! JSONEncoder().encode(testModel),
encoding: .utf8
) ?? "")
}
.padding()
}
}
저러쿵 했을때
잘 nil(NULL)로 들어가는걸 볼 수 있다. 필요하다면 Hahable이나 Equatable을 T의 필요조건으로 채택시켜서 에러를 안볼 수 있을 것이다.