How to Nil a object in Swift

人盡茶涼 提交于 2019-12-22 01:13:02

问题


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.



来源:https://stackoverflow.com/questions/30612740/how-to-nil-a-object-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!