The entire NSString API is available to call on any String value you create when type cast to NSString.
-
Empty String
let a: String = "" //String literal
var b: String = String() //initializer
b += "Hello"if a.isEmpty { //TODO }
Strings are Value Types
Copy/Not Reference-
Working with Characters
let s: String = "Hello World"
for i in s.characters {
print(i)
}let c: Character = "!" let cArr: [Character] = ["a", "b", "c"] var s: String = String(cArr)
Concatenating Strings and Characters
let a: String = "a"
let b = "b"
var c = a + b
let d: Character = "!"
var e: String = c.append(d)-
String Interpolation
let pi: Double = 3.14 var r: Double = 1.0 var s: String = "Circle square is \(pi*r*r)."
Character Count
let a: String = "Hello"
print("String a has (s.characters.count) characters.")-
String Indexes
let a: String = "Hello World"
a[a.startIndex] //H
a[a.endIndex] // error
a[a.endIndex.predecessor()] //d
a[a.startIndex.successor()] //elet newIndex = advance(a.startIndex, 6) a[a.newIndex] // W for index in indices(a) { print(\(a[index])) }
-
String Insert & Remove
var hello: String = "Hello"
hello.insert("!", atIndex: hello.endIndex) //Hello!
hello.splice(" World".characters, atIndex: hello.endIndex.predecessor()) //Hello World!
hello.removeAtIndex(hello.endIndex.predecessor()) //Hello Worldvar range = advance(hello.endIndex, -6)..<hello.endIndex hello.removeRange(range) //Hello
-
Comparing Strings
Unicode comparisonlet a: String = "ABC" let b: String = "DEF" let flag: Bool = a.hasPrefix(A) //true let flag2: Bool = b.hasSuffix(E) //false
-
UTF
let a = "Hello World" for bit in a.utf8 { var b: String.UTF8View = bit print(b) }