UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 18: using a function to solve the extra challenge?

Forums > 100 Days of SwiftUI

Hi everyone!

I struggled with the extra challenge of day 18 and the first solution I came up with, before finally using a property, was using a function. This is because the declaration for currency came up as a static func.

I was just wondering if using the function would be fine in real code as well, or if there's a problem with it. Here's what I came up with:

    func currencyFormatter() -> FloatingPointFormatStyle<Double>.Currency {
        .currency(code: Locale.current.currencyCode ?? "EUR")
    }

And then, calling it within the Text view:

 Section {
                    Text(grandTotal, format: currencyFormatter())
                } header: {
                    Text("Grand total")
                }

                Section {
                    Text(totalPerPerson, format: currencyFormatter())
                } header: {
                    Text("Amount per person")
                }

Everything worked as expected, but I'm still unsure!

1      

There are very few times when only one approach is possible. Usually there are several solutions possible. Using a function is fine, except your calls

Text(grandTotal, format: currencyFormatter)
…
Text(totalPerPerson, format: currencyFormatter)

should be

Text(grandTotal, format: currencyFormatter())
…
Text(totalPerPerson, format: currencyFormatter())

to not cause build errors.

Why one approach would be better than another will come with experience, the strategy chosen for the code design, complexity of the resulting code (think maintainability) and the flexibility of the code (can it be used in more situations with a simple modification to the code).

You could write an extension where, for example, you would end up with

Text(grandTotal)
    .currencyFormatter
…
Text(totalPerPerson)
    .currencyFormatter

1      

Hi, I appreciate the reply!

You're right about the parenthesis, I copied the code after implementing the property instead of the function, my bad. I've added them in there now.

I hope I will get the necessary insight over time to see when to apply which solution, it's quite hard now!

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.