Home > database >  Wrapping currency expression in a constant in SwiftUI
Wrapping currency expression in a constant in SwiftUI

Time:02-13

I am learning Swift and Xcode and there is a task that I have problems wrapping my mind around. There are three places where I use value formatter:

format: .currency(code: Locale.current.currencyCode ?? "PLN")

I packed it into a constant and it doesn't throw any errors:

let currencyFormatter = { (amount: Double) -> FloatingPointFormatStyle<Double>.Currency in
.currency(code: Locale.current.currencyCode ?? "PLN")
}

The execution though does throw several errors (they don't change if I swap the closure to void instead of accepting Double):

Text(totalPerPerson, format: currencyFormatter)

Some of the errors: 1.

Cannot convert value of type 'Double' to expected argument type '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput'
Initializer 'init(_:format:)' requires that '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput' conform to 'Equatable'

CodePudding user response:

The correct constant should be as

let currencyFormatter = FloatingPointFormatStyle<Double>.Currency.currency(code: Locale.current.currencyCode ?? "PLN")

CodePudding user response:

It seems that there is another variant of a viable answer to this question that puts greater emphasis on the type of the constant:

 let currencyFormatter: FloatingPointFormatStyle<Double>.Currency = .currency(code: Locale.current.currencyCode ?? "PLN")

But wouldn't find it without @Asperi's help.

  • Related