Reputation: 20412
I have a very generic function which needs to return AnyObject
:
func backgroundFunction(dm : DataManager) -> AnyObject {
...
}
however there are some cases where I would like to return an empty/null value
I thought about these two values:
nil
but it doesn't seem to be allowed: Type 'AnyObject' does not conform to protocol 'NilLiteralConvertible'
0
but when I test if that AnyObject value is 0 with value != 0
I get this error: Binary operator '!=' cannot be applied to operands of type 'AnyObject' and 'nil'
Is there any solution?
Upvotes: 4
Views: 7150
Reputation: 39081
Only an optional value can be set to nil or checked for nil. So you have to make your return type an optional.
func backgroundFunction(dm : DataManager) -> AnyObject? {
...
return nil
}
Upvotes: 13
Reputation: 20412
I found the 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
}
Upvotes: 1