ios 将 NSData 初始化为零 SWIFT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27278452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:53:24  来源:igfitidea点击:

init NSData to nil SWIFT

iosswiftnsdata

提问by cmii

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 而我还没有初始化。

回答by Hector Matos

One thing you can do is ensure your NSDataproperty is an optional. If the NSData object has not been initialized yet, then you can perform your if nilcheck.

您可以做的一件事是确保您的NSData财产是可选的。如果 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! You can simply do this:

因为 Swift 中的 optionals 默认设置为 nil,所以你甚至不需要初始赋值部分!你可以简单地这样做:

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

回答by keithbhunter

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)
}

回答by Daniel T.

If you want to set your datavariable to nil, just do data = nil. If you want to set it to be empty, then do data = NSData().

如果要将data变量设置为nil,只需执行data = nil. 如果要将其设置为空,请执行data = NSData().