david david - 1 year ago 108
Swift Question

Swift - How to check if var is nil?

I need to check if the last element in a dataArray is nil or not, so I am running this code:

if(dataArray.last == nil){
print("dataArray.last == nil");
} else {
print("dataArray.last != nil , last = " + String(dataArray.last));

The weird thing is that it is printing this:

dataArray.last != nil , last = Optional(nil)

It is saying that the last element is nil despite the if condition not being met. How is this possible?

Additionally, if I print
this is what is returned:

[itemData,itemData , itemData , nil , nil , nil].

Answer Source

first and last methods of array return optional value, that contains nil or element of array. Going forward, element of array can be nil by itself. Let me show easy example:

let dataArray: [String?] = ["a", nil]
let lastElement = dataArray.last

You think that lastElement have type String?, but it have type String?? instead. When you check dataArray.last for nil, you only confirm that array is not empty. I offer you to use optional binding instead:

if let lastElement = dataArray.last, _ = lastElement{         
    print("dataArray.last != nil , last = " + String(dataArray.last));        
    print("dataArray is empty OR last element of dataArray is nil");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download