Swift 中的反斜杠有什么作用?
What does backslash do in Swift?
在下面的代码行中,反斜杠告诉 Swift 做什么?
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
这就是所谓的字符串插值。当你想在字符串中嵌入变量的 value 时,你必须将变量名放在括号之间,并用反斜杠转义左括号。这样编译器就知道它必须在那里替换变量的值,而不是使用变量名的字符串文字。
有关该主题的更多信息,请查看 Swift 语言指南的 String interpolation 部分。
反斜杠在 Swift 中有一些不同的含义,具体取决于上下文。在您的情况下,这意味着字符串插值:
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
...等同于:
print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
但第一种形式更具可读性。另一个例子:
print("Hello \(person.firstName). You are \(person.age) years old")
这可能会打印类似 Hello John. You are 42 years old
的内容。比:
更清晰
print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")
在下面的代码行中,反斜杠告诉 Swift 做什么?
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
这就是所谓的字符串插值。当你想在字符串中嵌入变量的 value 时,你必须将变量名放在括号之间,并用反斜杠转义左括号。这样编译器就知道它必须在那里替换变量的值,而不是使用变量名的字符串文字。
有关该主题的更多信息,请查看 Swift 语言指南的 String interpolation 部分。
反斜杠在 Swift 中有一些不同的含义,具体取决于上下文。在您的情况下,这意味着字符串插值:
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
...等同于:
print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
但第一种形式更具可读性。另一个例子:
print("Hello \(person.firstName). You are \(person.age) years old")
这可能会打印类似 Hello John. You are 42 years old
的内容。比:
print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")