Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

Codable에 대하여 설명하시오. #31

Open Do-hyun-Kim opened 9 months ago

Do-hyun-Kim commented 9 months ago

Codable에 대하여 설명하시오.

🧐Encoding 이란?

🤔 Encoding 방식

스크린샷 2023-11-20 오후 6 16 19

🥹 Decoding 이란?

😊 JSONEncoder Method

🥳 JSONEncoder 제공 Method, properties

// where절을 통해 Encodable 채택한 파라메터만 받을 수 있도록 제약을 걸어두고 있다.
open func encode<T>(_ value: T) throws -> Data where T : Encodable

// Type properties
struct JSONEncoder.OutputFormatting
struct Track: Codable {
  let title: String
  let artistName: String
  let isStreamable: Bool
}

let smapleTrack = Track(title: "Love Lee", artistName: "AKMU", isStreamable: true)

do {
    let encoder = try JSONEncoder().encode(smapleTrack)
    // UTF - 8 Encoding
    if let jsonString = String(bytes: encoder, encoding: .utf8) {
        print(jsonString)
      //print: {"artistName":"AKMU","title":"Love Lee","isStreamable":true}
    }
    //print: 60bytes
    print(encoder)
} catch {
    print(error.localizedDescription)
}

🫣 JSONDecoder Method

스크린샷 2023-11-20 오후 6 15 51
struct Track: Codable {
  let title: String
  let artistName: String
  let isStreamable: Bool
}

let jsonData = """
{
  "artistName" : "Dua Lipa",
  "isStreamable" : true,
  "title" : "New Rules"
}
""".data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    let data = try decoder.decode(Track.self, from: jsonData)
    print(data)
} catch {
    print(error)
}

📝 참고 사이트

vichye-1 commented 9 months ago

Codable이란?

Codable Protocol의 구성

typealias Codable = Decodable & Encodable

codable을 이용한 encoding

import Foundation

struct introduce: Codable {
    var name: String
    var age: Int
}

let firstTime: introduce = .init(name: "Alice", age: 12)

let data1 = try? JSONEncoder().encode(firstTime)
let result = String(data: data1!, encoding: .utf8)!
print(result)

codable을 이용한 decoding

import Foundation

struct introduce: Codable {
    var name: String
    var age: Int

let data = """
{
    "name" : "Alice",
    "age" : 12
}
""".data(using: .utf8)!

let human = try? JSONDecoder().decode(introduce.self, from: data)

human?.name // "Alice"
human?.age // 12

출처

ronick-grammer commented 8 months ago

Codable 이란

📝 참고 사이트