Concatenate Integer with String in Swift

In this tutorial, we will learn how to concatenate integer with string in Swift with some easy examples.

It’s easy to concatenate two strings in Swift as we all know + is enough to do that task.

If you have come across this tutorial, I am pretty much sure that you have tried the below method and got an error like this.

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

If you do something like this:

let myInteger = 5
let myString = "Hello CodeSpeedy"
print(myInteger + myString)

It will throw an error like this.

overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String

The reason is pretty simple.

So we need to do the below in order to fix this.

Concatenate number and string in Swift

let myInteger = 5
let myString = "Hello CodeSpeedy"
print(String(myInteger) + myString)

Output:

5Hello CodeSpeedy

Interpolation to concatenate number with a string

let myInteger = 5
let myString = "Hello CodeSpeedy"
print("\(myInteger)\(myString)")

Or you can also do this:

let myInteger = 5
let myString = "Hello CodeSpeedy"
print("\(myInteger)"+"\(myString)")

For both of these programs, the output will be the same.

Leave a Reply

Your email address will not be published. Required fields are marked *