如何 Nil Swift 中的对象
How to Nil a object in Swift
如何将 nil 分配给 Swift 中的对象。如果直接分配我会出错。
这意味着您的 lastRecordedLocation
对象不是 Optional
类型。
如果您将 lastRecordedLocation 设为可选,例如:
var lastRecordedLocation:String?
您可以稍后为该对象设置 nil。
只有optional可以是nil
var lastRecordedLocation:CLLocation?
或者这个
var lastRecordedLocation:CLLocation!
请检查以下内容:
var lastRecordedLocation: String?
lastRecordedLocation = nil
如果你想要零 属性 ,你需要 Optional 值 lastRecordedLocation
要使对象为 nil,必须由 声明为 nil?马克。这意味着该值可以(可能)为零。所以声明为:
var lastRecordedLocation: String?
然后你可以将它设置为nil
lastRecordedLocation = nil
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
同样重要的是要注意:
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
希望对你有所帮助!
注意:如果您定义一个可选变量而没有提供默认值,该变量会自动为您设置为 nil:
var lastRecordedLocation: String?
// lastRecordedLocation is automatically set to nil
or
lastRecordedLocation = nil
我使用以下命令清空之前填充的数据类型变量
var jsonData = Data()
这个变量之前被JSON序列化了,但是占用了太多内存,所以我重新初始化它,大小又变成了0字节。
如何将 nil 分配给 Swift 中的对象。如果直接分配我会出错。
这意味着您的 lastRecordedLocation
对象不是 Optional
类型。
如果您将 lastRecordedLocation 设为可选,例如:
var lastRecordedLocation:String?
您可以稍后为该对象设置 nil。
只有optional可以是nil
var lastRecordedLocation:CLLocation?
或者这个
var lastRecordedLocation:CLLocation!
请检查以下内容:
var lastRecordedLocation: String?
lastRecordedLocation = nil
如果你想要零 属性 ,你需要 Optional 值 lastRecordedLocation
要使对象为 nil,必须由 声明为 nil?马克。这意味着该值可以(可能)为零。所以声明为:
var lastRecordedLocation: String?
然后你可以将它设置为nil
lastRecordedLocation = nil
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
同样重要的是要注意:
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
希望对你有所帮助!
注意:如果您定义一个可选变量而没有提供默认值,该变量会自动为您设置为 nil:
var lastRecordedLocation: String?
// lastRecordedLocation is automatically set to nil
or
lastRecordedLocation = nil
我使用以下命令清空之前填充的数据类型变量
var jsonData = Data()
这个变量之前被JSON序列化了,但是占用了太多内存,所以我重新初始化它,大小又变成了0字节。