Can't initialize a struct with a default value Can't initialize a struct with a default value ios ios

Can't initialize a struct with a default value


Swift 5.1:

Variables, marked with var are optional in constructors and their default value will be used. Example:

struct Struct {  var param1: Int = 0  let param2: Bool}let s1 = Struct(param2: false)           // param1 = 0, param2 = falselet s2 = Struct(param1: 1, param2: true) // param1 = 1, param2 = true

For older versions of Swift (< 5.1):

Default Initialization is all-or nothing for a Struct. Either you define defaults for all properties and you get an automatically generated initializer Struct1() plus an initializer with all of the properties, or you get only the initializer with all of the properties, including any that happen to have a set default value. You're going to have to implement a custom initializer.

struct Struct1 {    let myLet = "my let"    let myLet2: Bool    let myLet3: String    init(myLet2: Bool, myLet3: String) {        self.myLet2 = myLet2        self.myLet3 = myLet3    }}


Swift 5.1: The struct memberwise initialisation behaviour is changing in Swift 5.1 (which ships with Xcode 11) to behave more as you'd expect:

struct Struct1 {  var myVar = "my var"  let myLet2: Bool  let myLet3: String}// Swift 5.1 generates a memberwise init as: // init(myVar: String = "my var", myLet2: Bool, myLet3: String)

so the following code will now work in Swift 5.1:

let s1 = Struct1(myLet2: false, myLet3: "My url123") let s2 = Struct1(myVar: "var1", myLet2: false, myLet3: "My url123")

For more details see the relevant Swift evolution proposal


In swift 4

struct Struct1 {    let myLet: String?    let myLet2: Bool    let myLet3: String     init(myLet: String? = nil, myLet2: Bool, myLet3: String) {        self.myLet = myLet        self.myLet2 = myLet2        self.myLet3 = myLet3    }}