Search code examples
iosswiftalamofireios10swift4

How to check if a class model created using alamofire is nil in swift?


I have created class models using HTTP networking library Alamofire which contains following data:

class MyData: NSObject {
    var name = ""
    var params = PublicData()

    func initUserWithInfo(userInfo: [String : AnyObject]) {
           if let name = userInfo["name"] as? String {
                 self.name = name
           }
           if let params = userInfo["params"] as? ParamData {
                 self.params = params
           }
    }
}

class PublicData: NSObject {
    var city = ""

    func initUserWithInfo(userInfo: [String : AnyObject]) {
          if let city = userInfo["city"] as? String {
                 self.city = city
           }
    }
}

Now, when I am trying to check whether params is nil or not, it's giving the following warning message:

let data = MyData()
if data.params != nil {
}
Comparing non-optional value of type 'params' to nil always returns true

or

if data.params {
}

'params' is not convertible to 'Bool'

or

if data.rams as Bool {
}

Cannot convert value of type 'ImpressionObject' to type 'Bool' in coercion

how can I able to check if the nested model class is nil or not?


Solution

  • You are getting this error because you are initialing the value of params and can not be nil later on. If you want to make it optional than you should try below code

    class MyData: NSObject {
        var name = ""
        /// making variable optional
        var params: PublicData?
    
        func initUserWithInfo(userInfo: [String : AnyObject]) {
               if let name = userInfo["name"] as? String {
                     self.name = name
               }
               if let params = userInfo["params"] as? ParamData {
                     self.params = params
               }
        }
    }
    

    After that you should use it as below

    let data = MyData()
    if let parameters = data.params {
    }