Search code examples
iosswiftanyobject

How to Compare AnyObject Is <Null> or not?


I am writing below function to return value based on data objet that I passed to this method.

If we get data null I am trying to return "-" otherwise If I get any valid response I am returning value..

private func checkDataForValue(data: Optional<AnyObject>) -> String {
    if let value = data {
        let value1: AnyObject = //have to check <Null>
        if value === value1 {
            return "-"
        }
        return "\(value)"
    } else {
        return "-"
    }
}

My question How to compare null value here ..


Solution

  • Most likely you are looking to compare value with NSNull.

    You can update your code as follows:

    private func checkDataForValue(data: Any?) -> String {
        if let value = data {
            if value is NSNull != nil {
                return "-"
            } else if (value as? String)?.lowercased() == "<null>" {
                return "-"
            } else {
                return "\(value)"
            }
        } else {
            return "-"
        }
    }