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

SOLVED: Weird issue with DateComponentsFormatter

Forums > SwiftUI

I must be missing something horribly obvious, but the line that requests padding format creates 6 xcode errors! Consecutive declarations etc The examples I referred to in Apple docs and HWS seem to use this identical syntax?

import SwiftUI
import AVFoundation

struct TimerView: View {
    @State var startTape: AVAudioPlayer?
    @State private var elapsedTime: TimeInterval = 0
    @State private var showTimer = false
    @State private var startTime = Date.now

    let formatInt = DateComponentsFormatter()
    formatInt.zeroFormattingBehavior = .pad

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

        var body: some View {
            VStack {
                Text(formatInt.string(from: elapsedTime)!)
                    .onReceive(timer) { _ in
                            elapsedTime = Date().timeIntervalSince(startTime)
                    }

2      

let formatInt = DateComponentsFormatter()
formatInt.zeroFormattingBehavior = .pad

That second line can't appear where you have it. It needs to be inside a method or a computed property.

So do this instead:

lazy var formatInt: DateComponentsFormatter = {
    let formatter = DateComponentsFormatter()
    formatter.zeroFormattingBehavior = .pad
    return formatter
}()

This is what's called a lazy variable.

3      

Ha! Thanks @roosterboy That would have taken me a while to find based on the unhelpful error messages.

2      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.