iPeter
iPeter

Reputation: 1360

What will be `.floatValue` in swift

I have searched enough in the web but failed to find any solution to this problem. It is a very basic thing in Objective C but I am not able to find the swift version of this.

I have an array like below:

arrSearchResult = [["name":"Adam Richards","occupation":"Architect","address":"Kolkata","status":"Pending","points":"4.8"],
                       ["name":"Rupindar Bains","occupation":"Photography, Interior Decorator","address":"Pune","status":"Accepted","points":"2.9"],
                       ["name":"Ajit Kolethe","occupation":"Finance Expert, Payroll","address":"Mumbai","status":"Rejected","points":"1.2"],
                       ["name":"Bob Grant","occupation":"Finance Service","address":"Kolkata","status":"Pending","points":"4.8"],
                       ["name":"Rachel Hunter","occupation":"Photography, Interior Decorator","address":"Pune","status":"Accepted","points":"3.5"],
                       ["name":"Sylvia Sanders","occupation":"Finance Expert, Payroll","address":"Mumbai","status":"Pending","points":"1.7"],
                       ["name":"Brittany Ramirez","occupation":"Graphic Designer, Photography","address":"Gurgaon","status":"Rejected","points":"2.2"],
                       ["name":"Xanadu Lee","occupation":"Chef, Travel Guide","address":"Mumbai","status":"Accepted","points":"4.8"]]

In every index in the array there is a Dictionary. As you can see there is a key in the Dictionary as "points". I am storing some float value as String with respect to that key.

Now I want to check the value if it is greater then or less than to a particular value or not.

In Objc I can write,

if([[arrSearchResult objectAtIndex:indexPath.row] valueForKey:@"points"].floatValue < 2.0) {
    //Do something
}

I have tried:

let point = (arrSearchResult.object(at: indexPath.row) as! NSDictionary).value(forKey: "points") as AnyObject
if Int(point as! NSNumber) > 2.0 {
    //Do something
}

The error I am getting is:

Binary operator '>' cannot be applied to operands of type 'Int' and 'Double'

Upvotes: 2

Views: 167

Answers (2)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Try this instead:

if Double(point as! String)! > 2.0 {
    ....
}

Your point is actually stored as a String.

The numeric types in Swift are strongly typed. For instance, you can't directly compare an Int to Double without a type conversion first. The compiler error you are getting warns you about this:

Binary operator '>' cannot be applied to operands of type 'Int' and 'Double'

Upvotes: 1

vadian
vadian

Reputation: 285079

The (safe) Swift 3 equivalent is

if let result = arrSearchResult[indexPath.row] as? [String:String], 
   let pointString = result["points"], 
   let point = Double(pointString), point > 2.0 {

}

The array contains dictionaries with String keys and String values. The value for key points is also a string. The code checks all types.

Upvotes: 3

Related Questions