Search code examples
swift2nsdata

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!
.
.
.
}

Solution

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