【问题标题】:Assign a value to an enum case during initalization in Swift在 Swift 初始化期间为枚举案例赋值
【发布时间】:2021-10-19 12:51:22
【问题描述】:

我正在使用 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" 
  }
}

我希望能够以编程方式控制CodingKeys 枚举中分配的name 值,因此它将基于用户设备区域设置。

// English user
country.name // "United States"

// French user
country.name // "États Unis"

我有函数getUserLocale() 检查用户的语言环境并返回它的字符串值(english、french 等...)。
如何让它在枚举初始化期间运行,以便将语言环境值分配给 name 属性?

【问题讨论】:

  • 我认为您误解了 CodingKeys 枚举的使用,也许还有什么是枚举,因为您谈论它正在初始化。 CodingKeys 枚举用于帮助编码器和解码器在您的属性和 json 中的键之间进行映射,并且它不以任何方式可变。
  • @JoakimDanielson 感谢您的评论; afaik enum 有一个 init 方法,所以我认为可以在那里完成。实现我所描述的行为的替代方法是什么?
  • 您能否提供一个您尝试解析的 JSON 类型的示例,并指出用户本地如何解析该 JSON。我不太清楚您要实施什么行为。
  • 啊,是的,您可以从其关联值启动枚举案例。我以为你的意思是别的。除此之外,我同意 Scott 的观点,因为我并不真正了解您想要实现的目标。
  • 对不起。我已经编辑了这个问题,希望现在更清楚了。

标签: ios swift


【解决方案1】:

实现自定义解码应该可以工作。这是一个例子。

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)

【讨论】:

  • 有效!非常感谢,斯科特! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多