Quick handling of NSData

I have the following line:

let jsonResults = NSData(contentsOfURL: Fetcher.URLforLicenseInfo()) 

This compiles and runs fine, but if NSData initialization fails, I get an exception later in the code. I tried adding another line:

 if jsonResults != nil { ///blah, blah... 

but then the compiler complains "Cannot invoke '!=' with an argument list type '(NSData, NilLiteralConvertible)"

Should the compiler recognize the return type of the NSData initializer as optional?

+5
source share
2 answers

check data length: if(data.length > 0) ...

+3
source

NSData Initializer will never return nil . On the other hand, when you write jsonResults != nil , it means that jsonResults is expected Optional, but it is not.

The condition if jsonResults != nil {} does not make sense.

Instead, you can check the number of bytes contained in the jsonResults.length data jsonResults.length


When to use the if != nil ?

Consider the following example:

 func toJson() -> NSData? { return nil // dummy } let jsonResults:NSData? = toJson() // jsonResults must be optional if jsonResults != nil{ println(jsonResults!.length) // The number of bytes contained by the data object. } 

Beware: since jsonResults is a constant (aka let ) of its read-only variable, and you cannot change it in the future, even if this value got nil


Link

 extension NSData { // ... init(contentsOfURL url: NSURL) // ... } 
+2
source

Source: https://habr.com/ru/post/1203115/


All Articles