Initializing Data? in a Codable object

I have a codable object.

public struct Member : Codable {
  var name: String
  var data : Data?

  init(name: String, data: String ) {
    self.name = name
    self.data = Data.init(base64Encoded: data)
  }

}

when I create a variable

let foo = Member(name: "Alice", data: "Bob")

why is it that when I do ,

  let foo_data = try? JSONEncoder().encode(foo)

  print(String.init(data: foo_data!, encoding: .utf8))

I get just

"Optional("{\\"name\\":\\"Alice\\"}")\n"

The data object is always nil even though its Base64 and doesn't show up in the json.

Data.init(base64Encoded:) is used to initialise (i.e. decode) a Data from a String which is already base64-encoded. "Bob" is an invalid value - you meant "Qm9i".

If you want to encode the String, try this:

"Bob".data(using: .utf8)?.base64EncodedData()

ah I see. A bit tired so for some reason, I kept thinking Data.init(base64Encoded:) takes in a base64encodeable string and turns it to base 64 . Thanks . lol

I wouldn't recommend you store your data in your struct as Data, if you're going to be marshaling it back and forth between String and Data.

Instead, store and use the String, and then just encode/decode to Data in a custom implementation of init(from: Encoder) and encode(to: Encoder).

Terms of Service

Privacy Policy

Cookie Policy