0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift] Codableのenumでjsonの値がnil または 空の時にデコード失敗させない

Last updated at Posted at 2024-12-17

事象

こういう構造体でAPIのレスポンスを受け取りたいが、typeがnilやキーがない時にデコード失敗してしまう

struct Hoge: Decodable {
    let id: Int
    let type: HogeType?
}
enum HogeType: Int, Codable {
    case fuga = 1, piyo
}

対策

これをしてあげればHogeの構造体のデコードで失敗しなくなり、typeがnilやキーが存在しない時にはデコード失敗しなくなる
またはlet type: HogeType とすれば正しくデコード失敗してくれる

protocol CommonCodable: RawRepresentable<Int>, Codable {}
extension CommonCodable {
    // Optionalをサポートするinit(from:)のカスタム実装
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rawValue = try? container.decode(RawValue.self)
        if let value = Self(rawValue) {
            self = value
        } else {
            // RawValueがデコードできなかった場合、Optionalの場合はnilを返す
            if Self.self is Optional<Any>.Type {
                self = Optional<Any>.none as! Self
            } else {
                throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid raw value for \(Self.self)")
            }
        }
    }
}

enum HogeType: Int, CommonCodable {
    case fuga = 1, piyo
}

忘れてた
これも必要(まぁなくても書き方変えるだけで良いけども)

extension RawRepresentable {
    init?(_ rawValue: RawValue?) {
        guard let rawValue = rawValue else { return nil }
        guard let value = Self(rawValue: rawValue) else { return nil }
        self = value
    }
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?