简体   繁体   English

将NSData初始化为nil SWIFT

[英]init NSData to nil SWIFT

How can I init NSData to nil ? 如何将NSData初始化为nil?

Because later, I need to check if this data is empty before using UIImageJPEGRepresentation. 因为稍后,我需要在使用UIImageJPEGRepresentation之前检查此数据是否为空。

Something like : 就像是 :

if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

I tried data.length == 0 but I don't know why, data.length isn't equal to 0 while I haven't initialized. 我尝试了data.length == 0但是我不知道为什么,在我没有初始化的情况下,data.length不等于0。

One thing you can do is ensure your NSData property is an optional. 您可以做的一件事是确保您的NSData属性是可选的。 If the NSData object has not been initialized yet, then you can perform your if nil check. 如果NSData对象尚未初始化,那么您可以执行if nil检查。

It would look like this: 它看起来像这样:

var data: NSData? = nil
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

Because optionals in Swift are set to nil by default, you don't even need the initial assignment portion! 因为Swift中的选项默认设置为nil,所以你甚至不需要初始赋值部分! You can simply do this: 你可以这样做:

var data: NSData? //No need for "= nil" here.
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

If you want a nil NSData , then you can initialize it like this: 如果你想要一个nil NSData ,那么你可以像这样初始化它:

var data: NSData?

Then you can use: 然后你可以使用:

if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

If you are wanting empty data, then initialize it like this: 如果您想要空数据,请按以下方式初始化:

var data = NSData()

And to check that it is empty: 并检查它是否为空:

if data.length == 0 {
    data = UIImageJPEGRepresentation(image, 1)
}

If you want to set your data variable to nil , just do data = nil . 如果要将data变量设置为nil ,只需执行data = nil If you want to set it to be empty, then do data = NSData() . 如果要将其设置为空,则执行data = NSData()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM