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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.