Swift - Get to know Strings

Introduction

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:

Demo

var composingString = "Hello" 
composingString += " world" 
print(composingString)

Result

A string is a collection of characters, you can iterate through one as if it were a collection:

Demo

for character in "hello" 
{ 
    print(character) /*w  w w  .  j av a 2 s . co  m*/
}

Result

to see how many characters make up the string:

Demo

var composingString = "Hello" 
composingString += " world" 

print(composingString.count)/*from w  w  w . j  a va  2 s .c  om*/

Result

To change the case of a string you use the uppercased and lowercased methods, which return modified versions of the original string:

Demo

var s = "test".uppercased() 
print(s)/*from ww w  . j  av  a  2  s.  c  o  m*/
s = "TEST".lowercased()
print(s)

Result

To compare strings you can just use the == operator as you would with numbers:

Demo

let string1  : String = "Hello" 
let string2  : String = "Hel" + "lo" 
if string1 == string2 { 
    print("The strings are equal") 
}

Result

Swift strings are Unicode-aware.

For example:

Demo

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") 
}

Result

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:

Demo

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:

Demo

let name = "Jack" 
let age = 21 
let line = "My name is \(name). I am \(age) years old."

Related Topics

Exercise