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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With