1) The first code works because String
has an init method that takes an Int
. Then on the line
let widthLabel = label + String(width)
You're concatenating the strings, with the +
operator, to create widthLabel
.
2) Swift error messages can be quite misleading, the actual problem is Int
doesn't have a init
method that takes a String
. In this situation you could use the toInt
method on String
. Here's an example:
if let h = height.toInt() {
let heightNumber = number + h
}
You should use and if let
statement to check the String
can be converted to an Int
since toInt
will return nil
if it fails; force unwrapping in this situation will crash your app. See the following example of what would happen if height
wasn't convertible to an Int
:
let height = "not a number"
if let h = height.toInt() {
println(number + h)
} else {
println("Height wasn't a number")
}
// Prints: Height wasn't a number
Swift 2.0 Update:
Int
now has an initialiser which takes an String
, making example 2 (see above):
if let h = Int(height) {
let heightNumber = number + h
}