Home > Enterprise >  Initialise without passing any parameter in swift?
Initialise without passing any parameter in swift?

Time:09-27

I have one struct in which having few variables I am initialising that with parameter, but for one case I want to init without passing any parameter to it.

For example:

struct ABC {
    var a: PQR
    var b: string
    init (a: PQR, b: String){
        self.a = a
        self.b = b
    }

    func xyz() {

    }
}

ABC().xyz() // want to call like this
ABC(a:PQR, b:"").xyz() // NOT like this

CodePudding user response:

You need to give default values in initializer, like

struct ABC {
    var a: String
    var b: String

    init(a: String = "", b: String = "") {    // << here !!
        self.a = a
        self.b = b
    }
...

CodePudding user response:

@Asperi's answer is one way to do it, another way you can do it is by giving a default value to where the variable is defined. This way you don't need to define an init method, rather use 2 initializers provided. See the code below:

Here I first define the structs with default values,

struct ABC {
    var a: PQR = PQR() // Default PQR value
    var b: String = "" // Default String value

    func xyz() {

    }
}

struct PQR {
    var c: String = "PQR" // Default String value
}

You can use it as,

let a = ABC(a: PQR(c: "pqe")).xyz()
let b = ABC(b: "Hello").xyz()
let c = ABC().xyz()

Recall here that you don't define an init, but rather use the default init methods with parameters you fill only if you need to (aka Optional). See the image below, as no compiler errors are displayed, you can use it as defined above.

enter image description here

  • Related