18
votes

Hi I have a question about this code:

1)

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

2)

let height = "3"
let number = 4
let hieghtNumber = number + Int(height)

The first part is working just fine, but I don't get why the second one is not. I am getting the error 'Binary operator "+" cannot be applied to two int operands', which to me does not make much of sense. Can someone help me with some explanation?

2
See also the answer to this question. Essentially, if A is already declared as a Double of CGFloat or whatever, and B and C are integers, A = B + C will fail with this error message, which obscures the real issue and solution: A = Double(B+C). This question/answer is at the top of the Google search for this error; in some cases the other question's answer may be more helpful. - ConfusionTowers

2 Answers

17
votes

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
}
0
votes

What you need is this:

let height = "3"
let number = 4
let heightNumber = number + height.toInt()!

If you want to get an Int from a String you use toInt().