david david - 3 months ago 8
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
String(dataArray)
this is what is returned:

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

Answer

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));        
}else{
    print("dataArray is empty OR last element of dataArray is nil");
}
Comments