Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check condition with "<null>" in swift 3.0

Tags:

ios

swift

swift3

  1. I want to check that the maxprice is equal to "" this or not if it's "" then maxprice will become maxprice = 0

my Json

price = ({
    maxprice = "<null>";
    minprice = "<null>";
});

code

var Arr = NSArray()

Arr = result.value(forKey: "price") as! NSArray
let max = Arr.value(forKey: "maxprice")

if max == nil {
    self.MaxValue = 0
    self.MinValue = 0
}

else {
    let maxval =  (Arr.object(at: 0) as AnyObject).value(forKey: "maxprice") as! NSNumber
    let min =  (Arr.object(at: 0) as AnyObject).value(forKey: "minprice") as! NSNumber

    self.MaxValue = maxval
    self.MinValue = min
}

Error: Could not cast value of type 'NSNull' (0x102148918) to 'NSNumber' (0x10311c4a8).

like image 303
user8198079 Avatar asked Sep 18 '17 06:09

user8198079


2 Answers

You can also use is to check for the presence of a null:

if Arr.value(forKey: "maxprice") is NSNull {
    // do something with null JSON value here
}
like image 127
AshokPolu Avatar answered Oct 02 '22 06:10

AshokPolu


Swift 3.0

You can get this in short line of code using ?? as like below also we can say rescue operation.

let max = Arr.value(forKey: "maxprice") as? NSNumber ?? 0
like image 42
Jaydeep Vora Avatar answered Oct 02 '22 08:10

Jaydeep Vora