1. 서버에서 값이 nil로 들어오는 경우를 대비해 프로퍼티를 옵셔널 타입으로 정의해놓음.

  2. 그런데 만약 서버에서 내가 정의해 놓은 enum이 아닌 다른 타입으로 넘어오거나 nil 값으로 내려지는 경우는? 디코딩 에러남.

  3. 파싱 오류를 막기 위해선 default 값을 넣어줘야겠다고 생각.

decode()는 return 값이 non-optional
decodeIfPresent()는 return 값이 optional

decodeIfPresent는 받는 타입도 optional 이여야함.

프로퍼티가 옵셔널 값이면 나중에 쓸때 optional binding 해주기 귀찮을땐
decode() 를 사용하는게 나아보임.

키가 없을 때의 경우는 decodeIfPresent 나 try? 를 써야 함. (안그럼 key not found 에러남)

struct CounselorReview: Codable {
	1. let productType: SaleProductType  // 옵셔널 값으로 안쓰고 싶음
    2. let productType: SaleProductType?

	init(from decoder: Decoder) throws {
		let container = try decoder.container(keyedBy: CodingKeys.self)
    
		1. productType = (try? container.decode(SaleProductType.self, forKey: .productType)) ?? .none
		2. productType = try container.decodeIfPresent(SaleProductType.self, forKey: .productType) ?? SaleProductType.none
	}
}

enum SaleProductType: Int, Codable {
    case text = 1
    case onlineGroup = 3
    case offlineGroup = 4
    case voice = 11
    case video = 13
    case interpret = 12
    case psyTest = 15
    case none  // default 값 정의
}
profile
신비로운 iOS 세계로 당신을 초대합니다.

0개의 댓글