Nick Kohrn Nick Kohrn - 3 months ago 10
Swift Question

Why Are My Default Property Values Still Showing as Parameters in Init()?

I have a protocol that describes a marine water parameter that needs tested:

protocol Parameter {

var name: String { get }
var unit: Unit { get }
var value: Double { get }

}


I have a struct,
Calcium
, that conforms to
Parameter
:

struct Calcium: Parameter {

var name: String = "Calcium"
var unit: Unit = UnitDispersion.partsPerMillion
var value: Double

}


Since the
name
and
unit
parameters of
Calcium
have default values, why do I need to provide them in the
init
method? Shouldn't I only need to provide a value for
value
?

I am trying to understand protocol-oriented-programming and would really appreciate a little guidance here.

enter image description here

Answer
  1. This has nothing whatever to do with protocols.

  2. You do not have to provide an initializer for anything but the value. But you have not provided any initializer. Therefore the only initializer you have is the one provided automatically, and that initializer is the memberwise initializer which wants parameters for all your properties.

If you don't like that, write an initializer yourself:

struct Calcium: Parameter {
    var name: String = "Calcium"
    var unit: Unit = UnitDispersion.partsPerMillion
    var value: Double
    init(value:Double) {self.value = value}
}

Now it is legal to say:

let c = Calcium(value:2)