Home > database >  Empty initializer for swift structures
Empty initializer for swift structures

Time:01-17

Is it possible to initialize a swift struct without any values?

To summarize the idea, I'm creating a struct with two attributes, those attributes were filled when I called the init() method, as it should, but the problem is, I have a function inside this struct and I need to use it, in some cases, without filling the fields in the struct initializer.

I've tried adding the init(){} function, hoping that somehow it would work like the empty constructors in java, but I've got no success.

  struct Quiz {
     var pergunta: String
     var resposta: Bool

    init(pergunta: String, resposta: Bool) {
        self.pergunta = pergunta
        self.resposta = resposta
    }

    //Something like that
    init(){}


    func popularQuiz() -> Array<Quiz> {
        ...
    }
 }

Is there a way to do it or swift doesn't have the option to create a empty structure?

CodePudding user response:

The big question is why do you want to have an empty Quiz? What does an empty Quiz mean?

Those questions aside, you can only create an initializer with no parameters if all of the properties can be given default values or if the properties are optional.

struct Quiz {
    var pergunta: String = ""
    var resposta: Bool = false

    init(pergunta: String, resposta: Bool) {
        self.pergunta = pergunta
        self.resposta = resposta
    }

    init(){}
}

Now your empty init will work because all properties are fully initialized. But is that what you really want?

Another way to get the same result is to use default values on the parameters of the main initializer.

struct Quiz {
    var pergunta: String
    var resposta: Bool

    init(pergunta: String = "", resposta: Bool = false) {
        self.pergunta = pergunta
        self.resposta = resposta
    }
}

Now you can call:

Quiz()
Quiz(pergunta: "Some question", resposta: "Some Answer")
Quiz(pergunta: "Question with no answer")

Any of these still result in all properties being initialized.

The last option would be to make the properties optional instead of using special default values. But this adds more headache later.

struct Quiz {
    var pergunta: String?
    var resposta: Bool?

    init(pergunta: String, resposta: Bool) {
        self.pergunta = pergunta
        self.resposta = resposta
    }

    init(){}
}

The empty init will leave the properties as nil. But now you need to properly handle the optional values everywhere. Again, is that what you really want?

  • Related