I created a struct
and want to save it as a JSON-file.
struct Sentence { var sentence = "" var lang = "" } var s = Sentence() s.sentence = "Hello world" s.lang = "en" print(s)
...which results in:
Sentence(sentence: "Hello world", lang: "en")
But how can I convert the struct
object to something like:
{ "sentence": "Hello world", "lang": "en" }
Swift 4 introduces the Codable
protocol which provides a very convenient way to encode and decode custom structs.
struct Sentence : Codable { let sentence : String let lang : String } let sentences = [Sentence(sentence: "Hello world", lang: "en"), Sentence(sentence: "Hallo Welt", lang: "de")] do { let jsonData = try JSONEncoder().encode(sentences) let jsonString = String(data: jsonData, encoding: .utf8)! print(jsonString) // [{"sentence":"Hello world","lang":"en"},{"sentence":"Hallo Welt","lang":"de"}] // and decode it back let decodedSentences = try JSONDecoder().decode([Sentence].self, from: jsonData) print(decodedSentences) } catch { print(error) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With