Swift: how to set AnyObject to null or equivalent

I have a very general function that should return AnyObject

:

func backgroundFunction(dm : DataManager) -> AnyObject {
    ...
}

      

however there are some cases where I would like to return empty / null

I thought about these two values:

  • nil

but that doesn't seem to be allowed: Type 'AnyObject' does not conform to protocol 'NilLiteralConvertible'

  • 0

but when i test if this AnyObject value is 0s value != 0

i get this error: binary operator '! = 'cannot be applied to operands of type "AnyObject" and "nil"

Is there any solution?

+3


source to share


2 answers


Only optional values ​​can be set to nil or checked to nil. Thus, you must make your return type optional.



func backgroundFunction(dm : DataManager) -> AnyObject? {
    ...
    return nil
}

      

+12


source


I found a solution by returning an optional AnyObject:



func backgroundFunction(dm : DataManager) -> AnyObject? {

     if IHaveAValueToReturn {
         return TheValueToReturn
     }

     return nil
     // in case of optional AnyObject, you are allowed to return nil

}

      

+1


source







All Articles