How to Nil a object in Swift How to Nil a object in Swift ios ios

How to Nil a object in Swift


From Apple Documentation:

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

also very importante to notice:

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

I hope that helps you!


Please check below:

var lastRecordedLocation: String?lastRecordedLocation = nil


To nil the object, it has to be declared with nil by ? mark. This means that the value can (possibly) be a nil. So declare it as :

var lastRecordedLocation: String?

and then you can set it to nil

lastRecordedLocation = nil