无法在Swift中乘以两个字符串值
我从JSON的JSON中获得float值的浮点数
:
{
"result": {
"conversion_factor": {
"conv_factor": "0.820000"
}
"search_result": [
{
"service_details": [
{
"standard_rate_in_usd": "10.00",
现在我需要乘以conv_factor * standard_rate_in_in_in_usd
code:此代码仅首先使用此代码值得正确的剩下的剩下的剩余表现出了什么?
let indexData = searchResult?.result?.search_result?[indexPath.row]
if let servDetls = indexData?.service_details{
for oneSerdet in servDetls{
var stringPrice: String?
if var priceVal = Float(oneSerdet.standard_rate_in_usd!), var convVal = Float((searchResult?.result?.conversion_factor?.conv_factor)!) {
stringPrice = String(priceVal * convVal)
}
else{
stringPrice = ""
}
cell.priceLbl.text = "£ \(stringPrice ?? "") \(currData)"
}
}
I am getting float value in string format from JSON like below
JSON:
{
"result": {
"conversion_factor": {
"conv_factor": "0.820000"
}
"search_result": [
{
"service_details": [
{
"standard_rate_in_usd": "10.00",
now i need to multiply conv_factor * standard_rate_in_usd
code: with this code only first value coming correct remaining showing wrong why?
let indexData = searchResult?.result?.search_result?[indexPath.row]
if let servDetls = indexData?.service_details{
for oneSerdet in servDetls{
var stringPrice: String?
if var priceVal = Float(oneSerdet.standard_rate_in_usd!), var convVal = Float((searchResult?.result?.conversion_factor?.conv_factor)!) {
stringPrice = String(priceVal * convVal)
}
else{
stringPrice = ""
}
cell.priceLbl.text = "£ \(stringPrice ?? "") \(currData)"
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要转换为浮标:
You need to convert to floats:
尝试一下,希望这能解决您的问题
Try this, hope this will resolves your issue
您有多个问题:
您的construct
searchResult?.result?.conversion_factor?.conv_factor
对可选字符串进行评估:string?
。。
您不能乘以字符串。字符串不是数字。您需要将字符串转换为双重。但是,采用字符串的双初始化器也返回可选(例如,“ Apple”无法转换为双重。
这里是一些示例代码,可以使用2个可选字符串,请尝试将它们转换为双打,并且倍增
You have multiple problems:
Your construct
searchResult?.result?.conversion_factor?.conv_factor
evaluates to an Optional String:String?
.You can't multiply strings. Strings are not numeric. You need to convert your string to a Double. But the Double initializer that takes a string also returns an Optional (since "Apple", for example, can't be converted to a Double.
Here is some sample code that will take 2 Optional Strings, try to convert them to Doubles, and multiples them.
That outputs