Hemang
Hemang

Reputation: 27052

How to check, whether a Date is nil or not?

I have a class name Person having below setter and getter.

private var _signedDate:Date? = nil
var signedDate:Date {
    get {
        return _signedDate!
    }
    set (newDate) {
        _signedDate = newDate
    }
}

As I have a variable 'signedDate` – I want to make a check function to let a person knows if he has signed or not. So for that, I am thinking to write a function like this:

func hasSigned() -> Bool {
    if signedDate {
        return true
    }
    return false
}

Now the compiler giving me the following error:

'Date' is not convertible to 'Bool'.

In Obj-C, we could simply check for nil of a particular variable. But with the case of Swift, this has been changed.

What should I do?

With a case of String, there's a method: isEmpty(). But no such methods available for Date.

Upvotes: 0

Views: 10936

Answers (4)

vadian
vadian

Reputation: 285092

First of all, do not use private backing variables in Swift.

Just declare the variable this way, even assigning nil is not needed.

var signedDate : Date? 

Second of all, usually you check for nil at the moment you need the unwrapped value. If the check passes the if condition date is unwrapped (non-nil). Please read the paragraph Optional Binding in Swift Language Guide - The Basics

if let date = signedDate {
  print(date)
} else {
  // signedDate is nil
}

or with guard to exit a function / method

guard let date = signedDate else { return }
print(date)

However if you want a function which returns a Bool write

func hasSigned() -> Bool {
    return signedDate != nil
}

or as a computed variable

var hasSigned : Bool { 
   return signedDate != nil  
}

Upvotes: 1

Sudipto Roy
Sudipto Roy

Reputation: 6795

Just compare the instance of Date to nil , thats it ! :)

if _signedDate == nil
{
     print("Found Nil")
}

Upvotes: 1

Wajih
Wajih

Reputation: 4383

Just type:

return _signedDate != nil

Upvotes: 5

Benzi
Benzi

Reputation: 2459

In your code, you cannot forcibly unwrap _signedDate always when accessing signedDate since it will throw a run time error if _signedDate is nil.

Either have a default value for signedDate when _signedDate is nil, or expose signedDate to be also of type Date?.

One can check if a date is nil by using:

func hasSigned() -> Bool {
    if _signedDate == nil {
        return false
    }
    return true
}

To provide a default date (if it makes sense):

private var _signedDate:Date? = nil
var signedDate:Date {
    get {
        return _signedDate ?? Date() // or some valid date
    }
    set (newDate) {
        _signedDate = newDate
    }
}

Upvotes: 5

Related Questions