53

I need to concatenate a String and Int as below:

let myVariable: Int = 8
return "first " + myVariable

But it does not compile, with the error:

Binary operator '+' cannot be applied to operands of type 'String' and 'Int'

What is the proper way to concatenate a String + Int?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Begum
  • 645
  • 1
  • 6
  • 11

7 Answers7

81

If you want to put a number inside a string, you can just use String Interpolation:

return "first \(myVariable)"
jtbandes
  • 115,675
  • 35
  • 233
  • 266
62

You have TWO options;

return "first " + String(myVariable)

or

return "first \(myVariable)"
pkamb
  • 33,281
  • 23
  • 160
  • 191
H. Mahida
  • 2,356
  • 1
  • 12
  • 23
8

To add an Int to a String you can do:

return "first \(myVariable)"
pkamb
  • 33,281
  • 23
  • 160
  • 191
CW0007007
  • 5,681
  • 4
  • 26
  • 31
4

If you're doing a lot of it, consider an operator to make it more readable:

func concat<T1, T2>(a: T1, b: T2) -> String {
    return "\(a)" + "\(b)"
}

let c = concat("Horse ", "cart") // "Horse cart"
let d = concat("Horse ", 17) // "Horse 17"
let e = concat(19.2345, " horses") // "19.2345 horses"
let f = concat([1, 2, 4], " horses") // "[1, 2, 4] horses"

operator infix +++ {}
@infix func +++ <T1, T2>(a: T1, b: T2) -> String {
    return concat(a, b)
}

let c1 = "Horse " +++ "cart"
let d1 = "Horse " +++ 17
let e1 = 19.2345 +++ " horses"
let f1 = [1, 2, 4] +++ " horses"

You can, of course, use any valid infix operator, not just +++.

Grimxn
  • 22,115
  • 10
  • 72
  • 85
3

Optional keyword would appear when you have marked variable as optional with ! during declaration.

To avoid Optional keyword in the print output, you have two options:

  1. Mark the optional variable as non-optional. For this, you will have to give default value.
  2. Use force unwrap (!) symbol, next to variable

In your case, this would work just fine

return "first \(myVariable!)"

Ferdz
  • 1,182
  • 1
  • 13
  • 31
Sategroup
  • 955
  • 13
  • 29
2
var a = 2
var b = "Hello W"
print("\(a) " + b)

will print 2 Hello W

-3

Here is documentation about String and characters

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
Tomasz Szulc
  • 4,217
  • 4
  • 43
  • 79