Swift 在 Codable 內使用 Enum 值

常常我們在 JSON 會內會看到一個字串使用不同的值代表不同的定義,雖然我們可以使用 String 去接,但程式實在很醜,我們其實可以在 Codable 內使用 Enum,這樣一來我們的程式會變得乾淨許多,怎麼用呢?其實很簡單的喔!

swift 1

假設這是一個 JSON 字串,裡頭代表客戶資料。

{
  "CustomerType": "1", // CustomerType = 1: VIP, 2: 普通客戶
  "Balance": "2000"
}

那我們可以定義一個物件,來解析這個,假設這個物件長成下面。

struct Customer : Codable {
    
    enum CustomerType: String, CaseIterable, Codable {
        ///VIP客戶
        case VIP = "1"
        ///普通客戶
        case Others = "2"
        
        init(from decoder: Decoder) throws {
            self = try CustomerType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .Others
        }
        
        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            try container.encode(rawValue)
        }
    }

    /// 客戶類型
    var CustomerType : CustomerType?
    /// 銀行餘額
    var Balance : String?
}

這整篇的關鍵其實是在下列的函式,要記得隨著你的列舉名稱來做對應的修改。

init(from decoder: Decoder) throws {
   self = try CustomerType(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .Others
}
        
func encode(to encoder: Encoder) throws {
   var container = encoder.singleValueContainer()
   try container.encode(rawValue)
}

可以看到,我們其實已經把客戶類型 (CustomType) 的列舉變成了 Codable,這樣一來我們就可以直接在客戶類型的變數型態改接列舉值了,是不是相當方便呢?

如果你對 Swift 的列舉還不太熟,可以看一下「Swift 的 列舉(Enum) 教學」一文。

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments