每个字符串由不依赖于编码的Unicode字符组成,并支持在各种Unicode表示中访问这些字符
Swift的String类型是用Foundation的NSString类来桥接的。 Foundation还扩展了String以公开NSString定义的方法。 这意味着,如果您导入Foundation,则可以在String上访问这些NSString方法,而不进行转换。
String 字面量 let someString = "Some string literal value" var emptyString = "" // empty string literal var anotherEmptyString = String() // initializer syntax // these two strings are both empty, and are equivalent to each other
String 是值类型 字符串包含了character字母类型,也可以说是character组成的数组
for character in "Dog!🐶".characters { print(character) }
let catCharacters: [Character] = ["C","a","t","!","🐱"] let catString = String(catCharacters) print(catString) // Prints "Cat!🐱"
String Index String.Index let greeting = "Guten Tag!" greeting[greeting.startIndex] // G greeting[greeting.index(before:greeting.endIndex)] //! greeting[greeting.index(after:greeting.startIndex)] //u let index=greeting.index(greeting.startIndex,offsetBy:7) greeting[index] // a
String Insert
var welcome="hello"
welcome.insert("!",at:welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf:" there".characters,at:welcome.index(before:welcome.endIndex))
// welcome now equals "hello there!"
String Remove
welcome.remove(at:welcome.index(before:welcome.endIndex))
// welcome now equals "hello there"
let range=welcome.index(welcome.endIndex,offsetBy:-6)..
welcome.removeSubrange(range)
// welcome now equals "hello"
String.UTF8
for codeUnit in dogString.utf8 {
print("\(codeUnit)",terminator:"")
}
print("")
// 68 111 103 226 128 188 240 159 144 182