Boring guide to String and Characters in Swift

May 30, 20

String can be defined as a collection of Characters into a single variable.

var str: String = "This is a String"

Character is a single value of a String

var chat: Character = "!"
  • Both are defined using "" , but for Character we have to explicitly define the type otherwise the Swift compiler will infer it as a String

You can add Strings to Strings but not Character to Strings.

var str1 = "This is a "
var str2 = "String"
var str = str1 + str2
print(str)

You can convert a Character or a array or Characters in to a String

var charArray: [Character] = ["S", "t", "r", "i", "n", "g"]
var charStr = String(charArray)
print(charStr)
String

Multi-line Strings

Multiline Strings are defined using """ in Swift.

var multilineStr = """
This is a multiline String.
I am the second line
"""
print(multilineStr)
This is a multiline String.
I am the second line

The first new line is not shown as new a line. To create an extra line at top and bottom we need to leave an extra line empty.

var multilineStr = """

This is a multiline String.
I am the second line

"""
print(multilineStr)

This is a multiline String.
I am the second line

String interpolation

Mixing different types while creating a String without converting other types to String explicitly. You can also add expressions while interpolation String.

var name:String     = "John"
var age:Int         = 37
var height: Double  = 178.6
var isTall: Bool    = height > 170
print("\(name) is \(age) years old and is \(height) cms tall. He is of a  \(isTall ? "good" : "short") height")
John is 37 years old and is 178.6 cms tall. He is of a  good height

Iterating over a String

When we iterate over a String to get individual elements from it, we get them as Character type.

var name:String = "John"
for n in name {
    print(type(of: n))
}
Character
Character
Character
Character

Substrings

We can create Substrings from a String using different methods provided by the String or by subscripting.

  • When we create a substring, the result that we get is of type Substring.
  • It holds most of the same methods as String but its purpose is for short usage.
  • If we want to use the substring for longer periods, we should convert it into a String
var longString: String = "ThisIsJustALongContinuesString"
var jIndex = longString.firstIndex(of: "J") ?? longString.endIndex
var subString = longString[..<jIndex]
print("\(subString) is of Type \(type(of: subString))")
ThisIs is of Type Substring
  • Substring usually will occupy the same memory space from the original String to optimize the use of memory untill you modify the original String or the Substring.