Swi*_*ard 0 string string-interpolation swift
在下面的代码行中,反斜杠告诉 Swift 做什么?
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
Run Code Online (Sandbox Code Playgroud)
反斜杠在 Swift 中具有几种不同的含义,具体取决于上下文。在你的情况下,这意味着字符串插值:
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
Run Code Online (Sandbox Code Playgroud)
...是相同的:
print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
Run Code Online (Sandbox Code Playgroud)
但第一种形式更具可读性。另一个例子:
print("Hello \(person.firstName). You are \(person.age) years old")
Run Code Online (Sandbox Code Playgroud)
这可能会打印类似的内容Hello John. You are 42 years old。比以下内容清楚得多:
print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1511 次 |
| 最近记录: |