BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.