Last active
December 18, 2021 07:06
-
-
Save Scior/dbdcb72cc46a04656b69005a680f1c29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
@propertyWrapper | |
public struct DecodeOnly<T: Decodable> { | |
public var wrappedValue: T | |
public init(wrappedValue: T) { | |
self.wrappedValue = wrappedValue | |
} | |
} | |
extension DecodeOnly: Codable { | |
public init(from decoder: Decoder) throws { | |
self.wrappedValue = try T(from: decoder) | |
} | |
public func encode(to encoder: Encoder) throws {} | |
} | |
extension DecodeOnly: CustomDebugStringConvertible where T: CustomDebugStringConvertible { | |
public var debugDescription: String { | |
return wrappedValue.debugDescription | |
} | |
} | |
extension DecodeOnly: Equatable where T: Equatable { | |
public static func == (lhs: DecodeOnly<T>, rhs: DecodeOnly<T>) -> Bool { | |
return lhs.wrappedValue == rhs.wrappedValue | |
} | |
} | |
public extension KeyedEncodingContainer { | |
func encode<T: Decodable>(_ value: DecodeOnly<T>, forKey key: K) throws {} | |
} | |
do { | |
struct Hoge: Codable { | |
var id: Int | |
var name: String | |
var address: String | |
} | |
let testInput = #"{"id":1,"name":"aaa","address":"bbb"}"#.data(using: .utf8)! | |
let decoded = try JSONDecoder().decode(Hoge.self, from: testInput) | |
print(decoded) // Hoge(id: 1, name: "aaa", address: "bbb") | |
let hoge = Hoge(id: 1, name: "aaa", address: "bbb") | |
let encoded = try JSONEncoder().encode(hoge) | |
print(String(data: encoded, encoding: .utf8)!) // {"id":1,"name":"aaa","address":"bbb"} | |
} | |
do { | |
struct Fuga: Codable { | |
var id: Int | |
var name: String | |
@DecodeOnly var address: String | |
} | |
let testInput = #"{"id":1,"name":"aaa","address":"bbb"}"#.data(using: .utf8)! | |
let decoded = try JSONDecoder().decode(Fuga.self, from: testInput) | |
print(decoded) // Fuga(id: 1, name: "aaa", _address: "bbb") | |
let hoge = Fuga(id: 1, name: "aaa", address: "bbb") | |
let encoded = try JSONEncoder().encode(hoge) | |
print(String(data: encoded, encoding: .utf8)!) // {"id":1,"name":"aaa"} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment