Home > Software engineering >  How I set a default struct initializer to get rid on an Ambiguous init use error?
How I set a default struct initializer to get rid on an Ambiguous init use error?

Time:01-03

I have a SwiftUI View with two similar init blocks. The only thing different between them is the type of an Optional property (has a default value). Because of the fact that it is optional, when I call the view without it, I get an Ambiguous use of 'init' error.

I want the first init to be the default initializer for the View.

Here's what it looks like:

struct NewView: View {

  var a: String
  var b: String
  var c: AnyShapeStyle
  var d: String

  init(a: String, 
       b: String,
       c: LinearGradient =  LinearGradient(gradient: Gradient(colors: [Color.green, Color.blue]), startPoint: .top, endPoint: .bottom),
       d: String = "Linear") {
    
    self.a = a
    self.b = a
    self.c = AnyShapeStyle(c)
    self.d = d
  }

  init(a: String, 
       b: String,
       c: AngularGradient =  AngularGradient(colors: [.green, .blue], center: .center),
       d: String = "Angular") {
    
    self.a = a
    self.b = a
    self.c = AnyShapeStyle(c)
    self.d = d
  }
  ...
}

Hence calling the view like this would give me the error:

NewView(a: "a", b: "b")

CodePudding user response:

You can differentiate the initializers using different argument label.


struct NewView: View {
  ...
  init(name a: String, 
       b: String,
       c: AngularGradient =  AngularGradient(colors: [.green, .blue], center: .center),
       d: String = "Angular") {
    
    ...
  }
  ...
}

Now whenever you call the following then the initializer with LinearGradient will be used.

NewView(a: "a", b: "b")

And to call the initializer with AngularGradient write the following:

NewView(name: "a", b: "b")

Whenever you overload method make sure to write self explanatory argument label which will help the caller to choose the right method/initializer.

  • Related