How to Nil a object in Swift

Muruganandham K

How to assign nil to an object in Swift. I'm getting error if assigned directly.

enter image description here


From Apple Documentation:

nil cannot be used with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type

also very importante to notice:

Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types

I hope that helps you!


Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment


How to check object is nil or not in swift?

Realm Swift how to add observer to object type (nil)

In Swift, how do I avoid both optionals and nil object references?

How to return nil object in non void function - swift 2.1?

Swift iOS Firebase -If the FirebaseAuth.FIRUser Object isn't nil how is it possible for the .email on it to return nil?

Realm Object returning nil (Swift)

How to handle Core Data custom methods what return an object or nil in Obj C or Swift

check if any property in an object is nil - Swift 3

Swift: IBoutlet always returns nil object?

Encoding generic String object gives nil Swift

Swift Encodable: encode nil as an empty object

How to convert NSNull to nil in Swift?

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

How to check if imageView is not nil in swift?

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

How to check if an object is nil in Objective-C?

How to remove nil object from NSMutableArray?

How to cast nil to IOKit.IOHIDValueCallback in swift

Swift: how to set AnyObject to nil or equivalent

How to add nil value to a NSArray in swift?

Swift Optional type: how .None == nil works

How to add nil value to Swift Dictionary?

How to check for `nil` in while loop condition in Swift?

How to pass in a nil notification variable in Swift

How to safely unwrap nil values in swift?

How to check if NSDictionary is not nil in Swift 2

How does swift handle nil values in memory

How to write nil value in Firebase in Swift?

Swift - How to catch nil value in SQLite query?