SWIFT: How to set anyobject to nil or equivalent

I have a very general function that needs to return AnyObject:

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

But in some cases I want to return an empty/null value

I thought of these two values:< /p>

>No

But it seems not allowed: the type’AnyObject’ does not conform to the protocol’NilLiteralConvertible’

> 0

but when I test When the AnyObject value is 0, the value is! = 0 I get this error: Binary operator’! =’Can’t be applied to operands of ‘AnyObject’ and ‘nil’

Are there any solutions?

Only optional values ​​can be set to nil or checked to nil. So you must make your return The type becomes optional.

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

I have a very general function that needs to return AnyObject:

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

But in some cases I want to return an empty/null value

I thought about it These two values:

>No

But it seems not allowed: The type’AnyObject’ does not conform to the protocol’NilLiteralConvertible’

> 0

< p> But when I test whether the AnyObject value is 0, the value is! = 0 I get this error: Binary operator’! =’Can’t be applied to operands of ‘AnyObject’ and ‘nil’

Are there any solutions?

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

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

Leave a Comment

Your email address will not be published.