1

How to make LocalizedStingKey type conform to Codable protocol in Swift? A simple Person struct. If do not remove country property, compiler not work.

struct Person: Codable {
    let name: String
    let age: Int
    let description: LocalizedKeyString // more words in description property
}
Edwardai
  • 491
  • 4
  • 8
  • 1
    Why not just change to a string instead? You can always convert a `String` to a `LocalizedStringKey` whenever you need. – Sweeper Aug 08 '22 at 03:03
  • Thank you Sweeper. You reminded me, and I'll give it a try. – Edwardai Aug 08 '22 at 03:11
  • @Edwardai did u figure out how to use them? im running into some issues too. – geethsg7 Aug 08 '22 at 06:30
  • 1
    A quick way would be to have `let description: String`, and decode that from the JSON or Plist, etc. And use a computed var to get the localization: `var localizedDescription: String { LocalizedKeyString(description) }`. – Larme Aug 08 '22 at 06:36
  • @geethsg7 Hi, I have decided to use String type. Larme also provided a good solution. Thanks Larme :) – Edwardai Aug 11 '22 at 05:43

1 Answers1

1

I decided to use String type and not add computed property because properties in my custom type is a little more.

If use computed property, the following code work:

struct Person: Codable {
let name: String
let age: Int
let description: String

var localizedDescription: LocalizedStringKey {
    return LocalizedStringKey(description)
}

}

Edwardai
  • 491
  • 4
  • 8