0

I am new to Swift. I tried with this Swift link Detect a Null value in NSDictionaryNSDictionary, but I failed to do so.

Data:

"end_time" = "<null>"

Here is my code:

if endTime["end_time"] is NSNull {

    print("your session still available ")
 }
else{
   print("your session end \(endTime["end_time"])")
}

Every time it is going to else statement. May be I need to convert string to null or alternative solution. Could you help me please?

Thank you.

Community
  • 1
  • 1
cristan lika
  • 415
  • 1
  • 7
  • 22

2 Answers2

-1

Here's how you check null in swift:

let time = endTime["end_time"]
if  time != "<null>" {
    print("time is not <null>")
}
else
{
    print("time is <null>")
}
Anni S
  • 1,996
  • 19
  • 28
-1

You can create a NilCheck controller to check nil or null for various datatypes. For example i have created a function to remove null [if any] from the dictionary and store the array of dictionary in Userdefaults. Please be free to ask your queries :)

func removeNilAndSaveToLocalStore(array : [[String:Any]]) {

    var arrayToSave = [[String:Any]]()
    for place in array {

        var dict = [String:Any]()
        dict["AreaId"] =  NilCheck.sharedInstance.checkIntForNil(nbr: place["AreaId"]! as? Int)
        dict["AreaNameAr"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaNameAr"]! as? String)
        dict["AreaName"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaName"]! as? String)
        dict["GovernorateId"] = NilCheck.sharedInstance.checkIntForNil(nbr: place["GovernorateId"]! as? Int)
        arrayToSave.append(dict)
    }
    LocalStore.setAreaList(token: arrayToSave)
}

class NilCheck {

static let sharedInstance : NilCheck = {
    let instance = NilCheck()
    return instance
}()

func checkStringForNil(str : String?) -> String {

    guard let str = str else {
        return String() // return default string
    }
    return str
}
func checkIntForNil(nbr : Int?) -> Int {

    guard let num = nbr else {
        return 0 // return default Int
    }
    return num
} }
Mr. Bean
  • 4,221
  • 1
  • 19
  • 34