我正在使用CodingKey列舉將 JSON API 解碼為結構體,以便將語言鍵從回應映射到name結構體的屬性:
{
id: "1",
english: "United States",
french: "états Unis",
spanish: "Estados Unidos"
}
struct Country: Codable, Hashable, Identifiable {
let id: String
let name: String
enum CodingKeys : String, CodingKey {
case id
case name = "french"
}
}
我希望能夠以編程方式控制列舉中的分配name值,CodingKeys因此它將基于用戶設備區域設定。
// English user
country.name // "United States"
// French user
country.name // "états Unis"
我具備的功能getUserLocale(),對于用戶的區域,然后回傳它的字串值檢查(english,french,等...)。
我怎樣才能讓它在列舉初始化期間運行,以便它將區域設定值分配給name屬性?
uj5u.com熱心網友回復:
實作自定義解碼應該有效。這是一個例子。
let sampleJSON = """
{
"id": "1",
"english": "United States",
"french": "états Unis",
"spanish": "Estados Unidos"
}
"""
var userLocale = "english"
struct Country: Decodable, Hashable, Identifiable {
let id: String
let name: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
name = try values.decode(String.self, forKey: CodingKeys(rawValue: userLocale)!)
}
enum CodingKeys : String, CodingKey {
case id
case english
case french
case spanish
}
}
let decoder = JSONDecoder()
let country = try decoder.decode(Country.self, from: sampleJSON.data(using: .utf8)!)
debugPrint(country)
userLocale = "french"
let anotherCountry = try decoder.decode(Country.self, from: sampleJSON.data(using: .utf8)!)
debugPrint(anotherCountry)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326245.html
上一篇:如何添加本地視頻?斯威夫特
