Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to set AnyObject to nil or equivalent

Tags:

swift

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?

like image 295
Daniele B Avatar asked Dec 09 '22 03:12

Daniele B


1 Answers

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
}
like image 191
Arbitur Avatar answered Jan 12 '23 00:01

Arbitur