swift中的`.floatValue`是什么?

时间:2017-04-27 10:26:49

标签: swift

我在网上搜索得足够多,但未能找到解决此问题的方法。在Objective C中这是一个非常基本的东西,但我无法找到它的快速版本。

我有一个如下数组:

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"]]

在数组的每个索引中都有一个Dictionary。正如您所看到的,在词典中有一个键作为" points"。我将一些浮点值存储为关于该键的String。

现在我想检查值是否大于或小于特定值。

在Objc我可以写,

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

我试过了:

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

我得到的错误是:

  

二元运算符&#39;&gt;&#39;不能应用于&#39; Int&#39;类型的操作数和&#39; Double&#39;

2 个答案:

答案 0 :(得分:3)

(安全)Swift 3等价物是

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

}

该数组包含带有String个键和String值的字典。键points的值也是一个字符串。代码检查所有类型。

答案 1 :(得分:1)

请改为尝试:

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

您的point实际上存储为String

Swift中的数字类型是强类型。例如,如果没有首先进行类型转换,则无法直接比较IntDouble。您收到的编译器错误警告您:

  

二元运算符'&gt;'不能应用于'Int'和'Double'类型的操作数