String,Character
String 在 Swift 中使用双引号(”)作为界限:
let greeting = "Hello!" // greeting's type is String
Character 可以从string初始化,只要只包含一个字符:
let chr: Character = "H" // valid
let chr2: Character = "��" // valid
let chr3: Character = "abc" // invalid - multiple grapheme clusters
字符串插入值
String interpolation 允许注入一个表达式,可以是任何值,包括字符串,整数,浮点数和其他各种。
语法是用一个斜杠,后面紧跟着一对括号括起来的值:\(value)
。任何有效的表达式都可以出现在括号里,包括函数调用。
let number = 5
let interpolatedNumber = "\(number)" // string is "5"
let fortyTwo = "\(6 * 7)" // string is "42"
let example = "This post has \(number) view\(number == 1 ? "" : "s")"
// It will output "This post has 5 views" for the above example.
// If the variable number had the value 1,it would output "This post has 1 view" instead.
特殊的字符
- \0
空字符 - \
斜杠 - \t
tab符 - \v
纵向tab - \r
回车符 - \n
换行符 - \”
双引号 - \’
单引号 - \u{n}
Unicode 符号
比如:
let message = "Then he said,\"I \u{1F496} you!\""
print(message) // Then he said,"I �� you!"