Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate number with string in Swift

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?

like image 847
Begum Avatar asked Jul 09 '14 06:07

Begum


People also ask

What is string interpolation in Swift?

Swift String Interpolation 2) Means the string is created from a mix of constants, variables, literals or expressions. Example: let length:Float = 3.14 var breadth = 10 var myString = "Area of a rectangle is length*breadth" myString = "\(myString) i.e. = \(length)*\(breadth)"

How do I get the length of a string in Swift?

Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.


4 Answers

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

return "first \(myVariable)"
like image 193
jtbandes Avatar answered Oct 23 '22 22:10

jtbandes


You have TWO options;

return "first " + String(myVariable)

or

return "first \(myVariable)"
like image 21
H. Mahida Avatar answered Oct 23 '22 23:10

H. Mahida


To add an Int to a String you can do:

return "first \(myVariable)"
like image 8
CW0007007 Avatar answered Oct 23 '22 23:10

CW0007007


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 +++.

like image 4
Grimxn Avatar answered Oct 23 '22 22:10

Grimxn