Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init NSData to nil SWIFT

Tags:

ios

swift

nsdata

How can I init NSData to nil ?

Because later, I need to check if this data is empty before using 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.

like image 744
cmii Avatar asked Dec 03 '14 17:12

cmii


2 Answers

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

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:

var data: NSData? //No need for "= nil" here.
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}
like image 96
Hector Matos Avatar answered Oct 04 '22 11:10

Hector Matos


If you want a nil NSData, then you can initialize it like this:

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)
}
like image 23
keithbhunter Avatar answered Oct 04 '22 13:10

keithbhunter