2 hours ago · Tech · hide · 0 comments

For a project I’m working on I had a need for a Codable object which could be represented as a basic text string, and specifically not a JSON string. I was eventually able to find a solution so I thought I’d document it, partially to help anyone who has the same need but also invite anyone to correct me if there is a simpler way to accomplish this. Let’s say you have this struct: struct MyData { let text: String let number: Int } And you want to encode the data as a string in the following format: My text (12) The Encodable part of it is simple, just implement the encode method and return the formatted string in a single-value container: extension MyData: Encodable { func encode(to encoder: any Encoder) throws { var container = encoder.singleValueContainer() try container.encode("\(text) (\(number))") } } Decodable is a bit more work, but also rather straightforward. I’ve chosen to implement a constructor that can initialise the struct from a source string—using regular expressions…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.