david david - 4 months ago 6
Swift Question

How to check if var is nil ? swift

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

if(dataArray.last == nil){

print("dataArray.last == nil");

print("dataArray.last != nil , last = " + String(dataArray.last));

The weird thing is that I got this log:
dataArray.last != nil , last = Optional(nil)

So it says last is nil although the if condition was not met. how this happened ?

also I print
here is what I got :

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


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.last == nil");