Reputation: 4396
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?
Upvotes: 1
Views: 1562
Reputation: 543
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.
Upvotes: 1
Reputation: 5316
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)
Upvotes: 0
Reputation: 143319
You still need to cast the numbers into the same type so they can be added together, e.g:
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
, i.e:
let cost:Double = 82.5
So they need to be either explicitly cast to a Double
or a Float
to be added together.
Upvotes: 4