Reputation: 15476
"The Swift Programming Language" contains the following sample code:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
When I changed width
implicitly to Double:
let width = 94.4
a compiler error is created for the line let widthLabel = label + String(width)
:
Cannot invoke '+' with an argument list of type (String, String)
While I can convert the Double
var to String
by calling width.description
, I want to know:
String(Integer)
works but String(Double)
doesn't?String(var)
and var.description
on a numerical type (Integer, Float, Double, etc)?Upvotes: 1
Views: 3669
Reputation: 72810
The reason why you can't do that is because String
doesn't have an initializer accepting a double or a float, whereas it implements initializers for all integer types (Int, Uint, Int32, etc.).
So @derdida's solution is the right way to do it.
I discourage using the description
property. It is not meant to convert a double to a string, but to provide a human readable textual representation of a double. So, whereas today's representation coincides with the conversion:
let width = 94.5
println(width) // Prints "94.5"
tomorrow it can be changed to something different, such as:
ninety four point five
That's still human readable, but it's not exactly a conversion of double to string.
This rule is valid for all types (structs, classes, etc.) implementing the Printable
protocol: the description
property should be used to describe, not to convert.
Addendum
Besides using string interpolation, we can also use the old c-like string formatting:
let pi = 3.1415
let piString = String(format: "%0.2f", arguments:[pi])
let message = "Pi is " + String(format: "%0.2f", arguments:[pi])
println(message)
Upvotes: 4
Reputation: 14904
I would use this when you like to create a string value:
let width:Double = 94.4
let widthLabel = "The width is \(width)"
Upvotes: 1