init NSData to nil SWIFT

23,858

Solution 1

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

Solution 2

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)
}
Share:
23,858
cmii
Author by

cmii

Updated on May 09, 2020

Comments

  • cmii
    cmii almost 4 years

    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.

  • Daniel T.
    Daniel T. over 9 years
    FYI, In the first line, you don't need the = nil part. It will initialize to nil by default.