Swift 铸造值浮动返回零
遇到了一个奇怪的问题。我正在打印响应中的值,如下所示。在第一个print语句中,它将打印正确的值,例如Swift 铸造值浮动返回零,swift,Swift,遇到了一个奇怪的问题。我正在打印响应中的值,如下所示。在第一个print语句中,它将打印正确的值,例如可选(3.0),但是当我将此值转换为浮点值时,它将变为零。第二个print语句显示nil。不知道我做错了什么。有什么给我的建议吗?像这样的字典userInfoDictionary:[字符串:Any]? print("The rating is \(response.userInfoDictionary?[RequestedUserConstant.userRatingKey])") let us
可选(3.0)
,但是当我将此值转换为浮点值时,它将变为零。第二个print语句显示nil。不知道我做错了什么。有什么给我的建议吗?像这样的字典userInfoDictionary:[字符串:Any]?
print("The rating is \(response.userInfoDictionary?[RequestedUserConstant.userRatingKey])")
let userRating = response.userInfoDictionary?[RequestedUserConstant.userRatingKey] as? Float
print("The rating is now \(tutorRating)")
不要用
as?
操作符将其强制转换为:Float(response.userInfoDictionary?[RequestedUserConstant.userRatingKey])
不要用as?
操作符将其强制转换为:Float(response.userInfoDictionary?[RequestedUserConstant.userRatingKey])
试试这个:
let userRating = response.userInfoDictionary?[RequestedUserConstant.userRatingKey].floatValue
试试这个:
let userRating = response.userInfoDictionary?[RequestedUserConstant.userRatingKey].floatValue
两个可能的问题:
第一个是,您将响应.userInfoDictionary?[RequestedUserConstant.userRatingKey]
分配给userRating
,然后打印不同的变量,该变量的名称为tutorRating
第二个问题是,它不是@Hamish所说的浮动。两个可能的问题:
第一个是,您将响应.userInfoDictionary?[RequestedUserConstant.userRatingKey]
分配给userRating
,然后打印不同的变量,该变量的名称为tutorRating
第二个是,它不是@Hamish所说的浮点。这是因为默认情况下,浮点值在内部是双精度的。因此,安全的展开方式是as?加倍 例如:
if let speed = json["averageSpeed"] as? Double {
//If you need Flot value, simply type cast from Double to Float.
let floatvalue = Float(speed)
}
这是因为默认情况下,浮点值在内部是双精度的。因此,安全的展开方式是as?加倍 例如:
if let speed = json["averageSpeed"] as? Double {
//If you need Flot value, simply type cast from Double to Float.
let floatvalue = Float(speed)
}
尝试使用
as进行一次浮点(“您的值”)检查?字符串
而不是as?Float
@NiravD也为nil…它可能是一个双精度
而不是浮点
。打印什么(类型:response.userInfoDictionary?[RequestedUserConstant.userRatingKey])
输出?尝试使用as进行一次浮点(“您的值”)检查?字符串
而不是as?Float
@NiravD也为nil…它可能是一个双精度
而不是浮点
。打印什么(类型:response.userInfoDictionary?[RequestedUserConstant.userRatingKey]))
output?Float
没有接受Any
作为参数的init。Float
没有接受Any
作为参数的init。错误:“Any”类型的值没有成员“floatValue”错误:“Any”类型的值没有成员“floatValue”