-1

I have a struct that is used when parsing JSON data. I want one of the fields, name, to be a fixed name, see below...

struct QuestionConfiguration: Codable, DisplayOrderable {
    var name: String? = "QuestionConfiguration"
    
    var isRequired: Bool
    var displayOrder: Int
    var title: String = ""
    var questions: [Question]
}

Each time, when I then try and access a QuestionConfiguration object, name is nil.

I have tried using an init(), with parameters and without. I have tried String? and String.

Does anyone know how I can achieve this so that name is the same for each object, without having to pass it to the object?

Joseph
  • 691
  • 4
  • 18
  • 3
    Does [this](https://stackoverflow.com/q/44655562/5133585) answer your question? It seems like you just want to exclude `name` from the `Codable` conformance. – Sweeper Dec 15 '22 at 06:15
  • 2
    Alternatively, if you don't need to change `name`, just make it a `let` and it will be ignored. – Sweeper Dec 15 '22 at 06:19
  • Why is the ***fixed*** value mutable, and why is it optional? – vadian Dec 15 '22 at 08:04

1 Answers1

1

Simply by changing this line - var name: String? = "QuestionConfiguration" to this - let name = "QuestionConfiguration"

Full code -

struct QuestionConfiguration: Codable, DisplayOrderable {
        let name = "QuestionConfiguration"
        
        var isRequired: Bool
        var displayOrder: Int
        var title: String = ""
        var questions: [Question]
    }

Note - If property is fixed then you should not call it as variable b'coz variable means it may change

teja_D
  • 383
  • 3
  • 18