Note: Video is part of a Swift beginner series by MadApper (a.k.a. Paul Napier)
We are going to be covering string manipulation. Since we are going to be using strings frequently in our programs, it is good that we understand key functions such as concatenation, interpolation, string length, and comparison.
Concatenation is joining two strings together to create a new string. Since strings and variables are mutable, this can be easy. The first way of concatenating strings is using the + operator:
var string1 = "hello" var string2 = " world" var concat = string1 + string2 println(concat) //concat = "hello world"
You can also use the addition assignment operator (+=). We will cover various types of operators later in the tutorial. For now, know that
String1 += string2 is shorthand for
string1 = string1 + string2.
+= operators serve to concatenate strings with strings and strings with characters. However, creating a string that creates other variable types requires interpolation. To use string interpolation, simply wrap parentheses around any type you want to include in the strings and prefix it with a backslash. For example:
var interpolation = "i have eaten \(100) bananas today" // interpolation = "i have eaten 100 bananas today" This works even using variables: ```language-swift var bananas = 10 var interpolation = "i have eaten \(bananas) bananas today" // interpolation = "i have eaten 10 bananas today"
In Swift, getting the string length is done using the countElements method. For example, we want to get the number of characters in our string variable interpolation:
countElements(interpolation) // 29
The countElements method is actually a collection type method, which we’ll get to later. What Essentially the method is treating the string as a collection of characters and returning how many characters are in the string.
To compare two strings for equality, simply use the “equal to” operator
var str1 = "aa" var str2 = "aa" var matches = str1 == str2 // matches = true because str1 and str2 are equal to each other
Note that Swift is case-sensitive:
var str1 = "Aa" var str2 = "aa" var matches = str1 == str2 // matches is false because of case-sensitivity
In order to compare two strings without regard to case, you have two choices: convert each string to all uppercase characters or convert each string to all lowercase characters. For that, we use the properties uppercaseString or lowercaseString.
str1.lowercaseString // AA str2.lowercaseString // aa
Now let’s go back to our comparison:
var matches = str1.lowercaseString == str2.lowercaseString // matches is true again!