Swift: how to set AnyObject to nil or equivalent

Daniele B

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?

Arbitur

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
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to Nil a object in Swift

How to convert NSNull to nil in Swift?

In Swift, how do you check if an object (AnyObject) is a String?

How to handle launchOptions: [NSObject: AnyObject]? in Swift?

How to check object is nil or not in swift?

iOS Delegate is not being set and is returning nil (Swift)

How to check that the string is not nil in swift?

How to convert Tuple to AnyObject in Swift

How to assign a Dictionary to AnyObject in swift

Swift/iOS: How to use inout parameters in functions with AnyObject/Any or Pointers

Set UIButton Image in Swift - currently unwraps as nil

In Swift, how do I set every element inside an array to nil?

How to cast a struct to Anyobject in Swift 2?

Swift 2: Value of type 'Set<UITouch>' has no member 'anyObject'

Swift equivalent to set multiple values to a property

How to add an Array<String> to a Dictionary<String, AnyObject> in Swift 2

Swift if value is nil set default value instead

How to differentiate AnyObject (or Int) type in XCode 9 - new Swift compiler

How to check if imageView is not nil in swift?

How to convert [AnyObject?] to [AnyObject]

Swift: How to typecast an AnyObject to an NSArray in this situation?

How to convert a NSUSerdefaults AnyObject? to SWIFT Array so that I can append to it?

Swift: How to check if an AnyObject is nil or not?

How to convert <AnyObject> response in AnyObject after an Alamofire request with JSON in Swift?

Swift 2: How can i assign a dictionary to AnyObject?

How to set an Array<Object> inside a Dictionary<String, AnyObject> - Swift3

Swift3, How to add AnyObject in a dictionary?

How do I set a Swift dictionary nil value such that my server receives null for the key?

How to set the metadata of LPLinkView to nil