Kai
Kai

Reputation: 15476

Cannot convert Double to String

"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:

  1. Why String(Integer) works but String(Double) doesn't?
  2. Is there any difference between calling String(var) and var.description on a numerical type (Integer, Float, Double, etc)?

Upvotes: 1

Views: 3669

Answers (2)

Antonio
Antonio

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

derdida
derdida

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

Related Questions