dbconfession
dbconfession

Reputation: 1199

Swift 2 NSData as nil

My application sometimes crashes when it finds nil in an NSData variable. When I try to account for the error, it says "Value of type "NSData" can never be nil, comparison isn't allowed.

Also, I have initialized the field, data as var data = NSData() so I can't understand where nil would even come from.

if self.data != nil {
     self.data = data!
.
.
.
}

Upvotes: 0

Views: 249

Answers (2)

Code Different
Code Different

Reputation: 93191

You are confusing between the instance variable and a local variable.

  • self.data is the instance variable, which you have defined to be not nil
  • data is a local variable, possibly a returned value from some function that you called. It's nilable (i.e. NSData?)

If I were to make a guess, your code would look something like this:

class MyClas {
    var data = NSData()

    func someFunction() {
        let data = anotherFunction() // This returns an NSData?
        if self.data != nil {
            ....
        }
    }
}

Change it to this:

if data != nil {
    self.data = data!
}

You can also use optional binding:

if let data = data {
    // data is guaranteed to be non-nil in here
    self.data = data
}

Upvotes: 1

David Ganster
David Ganster

Reputation: 1993

You are comparing self.data with nil, not data. Hence, I suspect you never assign to self.data.

Upvotes: 1

Related Questions