1

"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)?
Kai
  • 15,284
  • 6
  • 51
  • 82

2 Answers2

4

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)
Antonio
  • 71,651
  • 11
  • 148
  • 165
1

I would use this when you like to create a string value:

let width:Double = 94.4
let widthLabel = "The width is \(width)"
derdida
  • 14,784
  • 16
  • 90
  • 139
  • but can you do it *implicitly* (i.e. without the "`:Double`" declaration)? – Michael Dautermann Sep 29 '14 at 06:03
  • Thanks for the pointer, but I do know I could do that. What I want to know is why is Integer supported but Double/Float aren't, and what's the difference between String(var) and var.description – Kai Sep 29 '14 at 07:12
  • I would imagine that Ints are supported because there is no ambiguity about their String representation, whereas floating point numbers have several representations and many possible precisions. – Grimxn Sep 29 '14 at 13:48