1

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.

Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
halim
  • 87
  • 2
  • 2
  • 11
  • 4
    I think this is not empty value, but default value. So, one of the most used default values for `Date` is for example `Date()` – Robert Dresler Dec 13 '18 at 08:02
  • 2
    More context might be helpful. Do you want to set an *initial value* or an *empty value*? The latter would be the Optional `nil` in Swift. – Martin R Dec 13 '18 at 08:32
  • 2
    Not all types accept empty initializers. `0` for `Int` has a meaning in addition/substraction. `1` would be the right empty initial value for an `Int` in multiplcation/division. Have you contemplated using optionals? – ielyamani Dec 13 '18 at 09:14

1 Answers1

4

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 :

  • Now : let date1 = Date()
  • Jan 1, 1970 at 12:00 AM : let date2 = Date(timeIntervalSince1970: 0)
  • Jan 1, 2001 at 12:00 AM : 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.

ielyamani
  • 17,807
  • 10
  • 55
  • 90