Tip Calculator in SwiftUI

Now that we've seen a taste of SwiftUI, let's dive into a real example and build an app. We'll have a first look at @State variables we can use to creating a binding between our state and our UI, and we'll run into a few puzzling errors and see how we can coax Xcode into giving us the right error message.

This is a companion discussion topic for the original entry at https://nsscreencast.com/episodes/397-swiftui-tip-calculator

I’ve found an interesting glitch with this app: it works well until you remove $-sign from the input text field, then after you add it back again and enter the amount - “tip” and “total” would remain zeros.

Nice find! I looked at the example and I think that this is perhaps a bug w/ the formatter: API on TextField. If you wanted to get around this I think you’d have to separate the double value from the string and use Combine to update them based on changes. This would give you the ability to force a “$” to always be there, etc.

One reasonable workaround is using iOS 15’s format: .currency option. I’ve updated the code sample to do this conditionally.

Thanks Ben. It does seem that there’s something going on with TextField + NumberFormatter. In swift REPL it could be confirmed, that a number could be extracted from a string if the locale is set:

1> import Foundation
2> var f = NumberFormatter()
3> f.numberStyle = .currency
4> f.number(from: "$10")
$R0: NSNumber? = nil
5> f.locale = .init(identifier: "en_US")
6> f.number(from: "$10")
$R1: NSNumber? = Int64(10)

But when used via SwiftUI's TextField that does not seem to work. Using format: .currency API does work though.

Thank you