1

I want to check if the print statement prints "Key: messageTimestamp" so that I can define let disucssionMessageTimestampKey = DiscussionMessage.CodingKeys.messageTimestamp.stringValue. But I am getting an error 'CodingKeys' is inaccessible due to 'private' protection level. I get this error when I try to access CodingKeys in the file where the struct is defined or a different file. What am I missing? And is there no way I can access the default CodingKeys?

struct DiscussionMessage: Codable {
    let message, userCountryCode, userCountryEmoji, userName, userEmailAddress: String
    let messageTimestamp: Double
    let fcmToken, question, recordingUrl, profilePictureUrl: String?
}

let disucssionMessageTimestampKey = "messageTimestamp"

print("Key: ", DiscussionMessage.CodingKeys.messageTimestamp.stringValue)
Parth
  • 2,682
  • 1
  • 20
  • 39
  • It isn't exactly clear what you are trying to do, but you haven't added a `CodingKeys` enum to your struct. – Paulw11 Jan 30 '21 at 06:22
  • @Paulw11 I want a string for the variable name. So messageTimestamp is the variable name and I want it returned as a string "messageTimestamp" so I can use it elsewhere. I explain it here: https://stackoverflow.com/questions/65952289/get-codables-property-names-as-strings-in-swift – Parth Jan 30 '21 at 06:25
  • Then you will need to explicitly add a `CodingKeys` enum to your struct that contains all of the properties in your struct. – Paulw11 Jan 30 '21 at 06:32
  • Yes, I noticed that from a different answer. Is there a way to auto-generate this enum? – Parth Jan 30 '21 at 06:32
  • No. You either rely on the automatic property mapping (which won't be accessible since it is `private`) or you have to explicitly add one. Honestly it would be simpler just to add static strings to your struct that defined the field name(s) you want to use. – Paulw11 Jan 30 '21 at 06:51
  • 1
    That sucks, especially since I have a different structure in mind where I will have to individually access each key name when storing the value for the property to firebase. – Parth Jan 30 '21 at 07:09

1 Answers1

1

I am using the following code. Not the most ideal solution, it would be a lot better if I could access the default CodingKeys

struct DiscussionMessage: Codable {
    let message, userCountryCode, userCountryEmoji, userName, userEmailAddress: String
    let messageTimestamp: Double
    let fcmToken, question, recordingUrl, profilePictureUrl: String?
    
    enum CodingKeys: CodingKey {
        case message, userCountryCode, userCountryEmoji, userName, userEmailAddress
        case messageTimestamp
        case fcmToken, question, recordingUrl, profilePictureUrl
    }
}
Parth
  • 2,682
  • 1
  • 20
  • 39