简体   繁体   中英

arithmetic within string literal in Swift

Playing with Swift, I found something awkward error.

let cost = 82.5
let tip = 18.0
let str = "Your total cost will be \(cost + tip)"

This works fine as I expect, but

let cost = 82.5
let tip:Float = 18
let str = "Your total cost will be \(cost + tip)"

would not work with error

could not find member 'convertFromStringInterpolationSegment' 
let str = "Your total cost will be \(cost + tip)"

The difference between two example is declaring tip constant to explicitly float or not. Would this be reasonable result?

You still need to cast the numbers into the same type so they can be added together, eg:

let cost = 82.5
let tip:Float = 18
let str = "Your total cost will be \(Float(cost) + tip)"

By default real number literals are inferred as Double , ie:

let cost:Double = 82.5

So they need to be either explicitly cast to a Double or a Float to be added together.

Values are never implicitly converted to another type.

let cost = 82.5
let tip:Float = 18
let str = "Your total cost will be \(cost + tip)"

In the above example it is considering cost as double & you have defined tip as float, so it is giving error.

Rather specify the type of cost as float as shown below

let cost:Float = 82.5

Hope it will solve your problem.

In your code cost in inferred to be of type Double .

In your first (working) example tip is also inferred to be Double and the expressions cost + tip is an addition of two Double values, resulting in a Double value.

In your second (not working) example tip is declared to be Float therefore the expressions cost + tip is an error. The error message is not very informative. But the problem is that you are adding a Double to a Float and in a strongly statically typed language you will not have automatic type conversions like you had in C or Objective C.

You have to do either Float(cost) + tip or cost + Double(tip)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM