Swift strings are sequences of Unicode characters.
You can create an empty string by creating a string literal with nothing in it:
let emptyString = ""
You can also create an empty string using the String type's initializer:
let anotherEmptyString = String()
let keyword defines a string constant.
Strings can be combined in a manner similar to numbers using the + and += operators:
var composingString = "Hello" composingString += " world" print(composingString)
A string is a collection of characters, you can iterate through one as if it were a collection:
for character in "hello" { print(character) /*w w w . j av a 2 s . co m*/ }
to see how many characters make up the string:
var composingString = "Hello" composingString += " world" print(composingString.count)/*from w w w . j a va 2 s .c om*/
To change the case of a string you use the uppercased and lowercased methods, which return modified versions of the original string:
var s = "test".uppercased() print(s)/*from ww w . j av a 2 s. c o m*/ s = "TEST".lowercased() print(s)
To compare strings you can just use the == operator as you would with numbers:
let string1 : String = "Hello" let string2 : String = "Hel" + "lo" if string1 == string2 { print("The strings are equal") }
Swift strings are Unicode-aware.
For example:
let c1 = "Caf\u{302}" let c2 = "Cafe\u{301}" if c1 != c2 { //w w w. j av a2s . co m print("The strings are not equal") }
In Swift == checks if they have the same value.
To see if two variables refer to the same object, you use the === operator.
Swift can search strings and check the suffix or prefix of a string:
if "Hello".hasPrefix("H") { print("String begins with an H") } if "Hello".hasSuffix("llo") { print("String ends in llo") }
Swift strings support interpolation via \() syntax inside a string:
let name = "Jack" let age = 21 let line = "My name is \(name). I am \(age) years old."