How to Nil a object in Swift

2019-04-17 23:08发布

问题:

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

回答1:

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!

.



回答2:

Please check below -

var lastRecordedLocation: String?
lastRecordedLocation = nil


回答3:

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


回答4:

NOTE : If you define an optional variable without providing a default value, the variable is automatically set to nil for you:

var lastRecordedLocation: String?
// lastRecordedLocation is automatically set to nil
   or
lastRecordedLocation = nil


回答5:

That means your lastRecordedLocation object is not Optional type. If you make lastRecordedLocation as Optional such as:

var lastRecordedLocation:String?

You can set nil to that object later.



回答6:

Only optional can be nil

var lastRecordedLocation:CLLocation? or this var lastRecordedLocation:CLLocation!



回答7:

if you want nil the property , you need the Optional value for the lastRecordedLocation



回答8:

I used the following to empty a previously filled Data type variable

var jsonData = Data()

The variable had been used for JSON serialisation before but was taking up too much memory, so I just reinitialised it and the size becomes 0 bytes again.