-1

I have a custom data type:

struct Amount: ExpressibleByFloatLiteral, Codable {
    typealias FloatLiteralType = Double
    
    init(floatLiteral value: Double) {
        self.value = value
    }
    
    init(value: Double) {
        self.value = value
    }
    
    var value: Double
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(NSDecimalNumber(value: value).stringValue)
    }
}

And when I create model with it:

struct Car {
  var cost: Amount
}

var car = Car(cost: 1.5)

But when I set double typed value to model it not be inited:

var cost: Double = 1.5

var car = Car(cost: cost) // it won't be inited

Cannot convert value of type 'Double' to expected argument type 'Amount'

How to set double value to custom type?

aturan23
  • 4,798
  • 4
  • 28
  • 52
  • 1
    You seem to be doing some custom encoding in `Amount`. Is that why you didn't use the `typealias` solution as I suggested in your [previous post](https://stackoverflow.com/questions/64726152/swift-how-init-value-of-model-without-model-casting)? – Sweeper Nov 07 '20 at 09:56
  • You have lots of options: `Car(cost: Amount(value: cost))`, or write a `init` for `Car` that takes a `Double` so you don't have to write `Amount` every time you create a `Car`, but I'm guessing you have some restrictions? – Sweeper Nov 07 '20 at 09:59
  • @Sweeper when encoding Double numbers sometimes it will be incorrect typed. Like 1.2 => 1.1999999999. And for fix it I created custom type – aturan23 Nov 07 '20 at 09:59
  • @Sweeper Im working with large project. And I search easiest way for refactoring just Double to Amount – aturan23 Nov 07 '20 at 10:01
  • In you example your are using a variable and not a literal value when calling the constructor and why not use Decimal instead of Double when dealing with fixed number of decimals – Joakim Danielson Nov 07 '20 at 11:10

1 Answers1

0

You are trying to initialize your car with a Double but it expects an Amount. They are two different type even though they both conform to ExpressibleByFloatLiteral.

let cost: Amount = 1.5
let car = Car(cost: cost) // it works
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571