스위프트 Codable은 Swift에서 사용되는 프로토콜로, 데이터를 직렬화(serialization)하고 역직렬화(deserialization)할 수 있게 해준다.
이는 데이터를 다양한 형식으로 변환하고, 저장하거나 전송하기 위해 사용된다. Codable 프로토콜은 두 개의 서브 프로토콜인 Encodable과 Decodable로 구성된다.
- Encodable: Encodable 프로토콜은 데이터를 인코딩할 수 있는 타입이다. 이 프로토콜을 준수하는 타입은 JSON, Property List 등과 같은 형식으로 데이터를 인코딩할 수 있다.
- Decodable: Decodable 프로토콜은 데이터를 디코딩할 수 있는 타입이다. 이 프로토콜을 준수하는 타입은 JSON, Property List 등과 같은 형식으로부터 데이터를 디코딩할 수 있다.
Codable 프로토콜을 사용하여 Swift에서 모델 객체를 정의할 때는 다음과 같이 구현한다:
또한 이 이 Codable 구조체를 JSON 형식으로 인코딩하거나 JSON 데이터를 디코딩할 수 있다.
구뿐만 아니라 Json 데이터를 파싱하고 Mapping 하는 부분에서 Codable 사용 하여 자동으로 Mapping되어지는 형식
그러면 하나의 Model 혹은 객체를 만들어 사용할수 있다.
하나의 예시로 남기자면
let person = Person(name: "John", age: 30)
// 인코딩 let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(person) {
// JSON 문자열로 변환
let jsonString = String(data: encodedData, encoding: .utf8)
print(jsonString)
}
// 디코딩 let json = """
{
"name": "Jane",
"age": 25
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
if let decodedPerson = try? decoder.decode(Person.self, from: json) {
print(decodedPerson.name) // "Jane"
print(decodedPerson.age) // 25
}
위의 예시에서는 JSONEncoder와 JSONDecoder를 사용하여 데이터를 인코딩하고 디코딩하는 과정을 보여준다. Codable 프로토콜을 준수하는 타입은 다양한 형식으로 데이터를 다룰 수 있으며, 이를 통해 데이터의 직렬화와 역직렬화를 쉽게 수행할 수 있다.
내가 사용하고 있는 Codable + Model 객체 + JSONEncoder + JSONDecoder + 자동 Mapping 예시 이다.
struct LiveStreamJson: Codable {
var result:String
var result_msg:String
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let m_result = try? container.decode(String?.self, forKey: .result) {
result = m_result
}else{
result = ""
}
if let m_result_msg = try? container.decode(String?.self, forKey: .result_msg) {
result_msg = m_result_msg
}else{
result_msg = ""
}
}
'iOS, Swift 개발' 카테고리의 다른 글
iOS 탈옥 체크 로직 구성(Swift) (1) | 2024.05.07 |
---|---|
iOS 웹뷰 with 스토리보드, WkWebview (0) | 2024.04.25 |
Swift UITableView의 리스트 Value 변경 방법 (0) | 2024.04.16 |
Swift 싱글턴 패턴(Singleton Pattern) (0) | 2024.04.16 |
Swift Dictionary, Array nil 체크 (0) | 2024.04.16 |