I have two string type value i want subtract these two value and store the result in third var.how i subtract these two string type value.
let planPrice = plansArray?[i].spplan_price ?? ""
let adjustPrice = plansArray?[i].adjustedAmount ?? ""
let finalPrice = planPrice-adjustPrice
CodePudding user response:
First convert string values than make subtraction
let planPrice = Double(plansArray?[i].spplan_price ?? "") ?? 0.0
let adjustPrice = Double(plansArray?[i].adjustedAmount ?? "") ?? 0.0
let finalPrice = planPrice-adjustPrice
CodePudding user response:
You can't do math on strings. You have to convert them to a numeric type like Double first.
Double has a "failable initializer" that takes a string. If the string can't be converted to a Double, it returns nil.
I would advise against using force-unwrapping as in Nabeel's answer. If you do that and either of the Strings can't be converted, your app will crash.
Instead I would replace a nil result with 0. The following code would work:
let planPriceString = plansArray?[i].spplan_price ?? ""
let adjustPriceString = plansArray?[i].adjustedAmount ?? ""
let planPrce = Double(planPriceString) ?? 0.0
let adjustPrice = Double(adjustPriceString) ?? 0.0
let finalPrice = planPrice - adjustPrice