Concatenate number with string in Swift
Solution 1:
If you want to put a number inside a string, you can just use String Interpolation:
return "first \(myVariable)"
Solution 2:
You have TWO options;
return "first " + String(myVariable)
or
return "first \(myVariable)"
Solution 3:
To add an Int to a String you can do:
return "first \(myVariable)"
Solution 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 +++
.