Initialising structs
When you have a private constant in your struct, you will need to specify a constructor (ie. an init
) in order to initialise it using the parameters.
i.e.
struct Cake {
var cost: Double { return rawAmount.asDouble }
private let rawCost: Decimal
enum CodingKeys: String, CodingKey {
case rawCost = "amount" // server is sending a Decimal but we want to use a Double
}
}
So if you want to use the above struct
, ideally you would write:
let cake: Cake = .init(cost: 7.22)
However you can't do that, it will only want to initialise from Data
or Decoder
.
You need to explicitly write an initialiser inside the struct:
init(cost: Double) {
rawCost = Decimal(cost)
}