I'm very new to swift.
How to set empty value for Date
type in Swift to be used in declarations?
Like:
var string: String = ""
for String
type
var integer: Int = 0
for Int
type.
Thank you.
I'm very new to swift.
How to set empty value for Date
type in Swift to be used in declarations?
Like:
var string: String = ""
for String
type
var integer: Int = 0
for Int
type.
Thank you.
From the documentation :
A Date value encapsulate a single point in time, independent of any particular calendrical system or time zone. Date values represent a time interval relative to an absolute reference date.
In other terms, a date is nothing but a TimeInterval
, A.K.A a Double
representing the number of seconds since a reference date. Then, an empty initializer for Date
would be the one that returns a date 0 seconds away from that reference date. It all comes down to choosing the reference date :
let date1 = Date()
let date2 = Date(timeIntervalSince1970: 0)
let date3 = Date(timeIntervalSinceReferenceDate: 0)
You can choose a certain date as a reference if it makes sense to you. Examples: Date.distantPast
, Date.distantFuture
, ...
Now, if you want a variable to have a certain type, but no value, then use optionals and set their values to nil
:
var date4: Date? = nil
Later on, when you want to actually use the variable, just set it to a non-nil value:
date4 = Date(timeInterval: -3600, since: Date())
To use the actual value, you'll have to unwrap it using optional binding or the likes of it.