0

So basically what I'd like to do is have a date object

let unixTime = Date().timeIntervalSince1970.advanced(by: -30)

and have unixTime change as the seconds pass so that unixTime is offset from the current time without me having to increase the value myself. Is there a way to do that in Swift?

1 Answers1

0

Instead of declaring unixTime as a constant, declare it as a computed variable.


For example, if this code is part of a struct or class, I'd do this:

struct Test {
    var unixTime: Date {
        Date().timeIntervalSince1970.advanced(by: -30)
    }

    func tion() {
        //do stuff
    }

    ...
}

If you need it in an imperative context (such as a script) or you don't want to clutter the namespace of your type, you can declare it locally:

...
doStuff()
var unixTime: Date {
    Date().timeIntervalSince1970.advanced(by: -30)
}
...

Either way, you can refer to it in the same way as you are doing now, but it will be recomputed every time.

Sam
  • 2,350
  • 1
  • 11
  • 22