nsstring-在Swi中将数字与字符串连接

我需要将StringInt连接起来,如下所示:

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

但是它无法编译,并显示错误:

二进制运算符'+'不能应用于'String'和'Int'类型的操作数

连接字符串+整数的正确方法是什么?

Begum asked 2020-06-30T05:41:03Z
6个解决方案
67 votes

如果要在字符串中放入数字,则可以使用“字符串插值”:

return "first \(myVariable)"
jtbandes answered 2020-06-30T05:41:22Z
48 votes

您有两个选择;

return "first " + String(myVariable)

要么

return "first \(myVariable)"
H. Mahida answered 2020-06-30T05:41:46Z
5 votes

要将Int添加到字符串中,可以执行以下操作:

return "first \(myVariable)"
CW0007007 answered 2020-06-30T05:42:06Z
4 votes

如果您要执行很多操作,请考虑使用运算符以使其更具可读性:

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"

当然,您可以使用任何有效的中缀运算符,而不仅仅是+++

Grimxn answered 2020-06-30T05:42:31Z
3 votes

在声明过程中使用!将变量标记为可选时,将出现return "first \(myVariable!)"关键字。

为了避免在打印输出中使用Optional关键字,您有两个选择:

  1. 将可选变量标记为非可选。 为此,您将拥有提供默认值。
  2. 在变量旁边使用强制展开return "first \(myVariable!)"符号

在您的情况下,这会很好

return "first \(myVariable!)"

Sategroup answered 2020-06-30T05:43:08Z
0 votes

这是有关字符串和字符的文档

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
Tomasz Szulc answered 2020-06-30T05:43:29Z
translate from https://stackoverflow.com:/questions/24646794/concatenate-number-with-string-in-swift