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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.