Concatenate number with string in Swift

后端 未结 6 1490
暖寄归人
暖寄归人 2020-12-14 05:57

I need to concatenate a String and Int as below:

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

But it do

6条回答
  •  太阳男子
    2020-12-14 06:06

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

    func concat(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 +++ (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 +++.

提交回复
热议问题