Table of Contents:
- String Literals
- Concatenating Strings
- The length of a String
- Split a string into an array
- Join the string from array of strings (characters)
- Reverse the string
- Check if string contains the substring
This article explains Swift String type. You can experiment and test this code on swiftplayground. All experiments are doable in Swift 5 and later.
String literal in Swift is text within a pair of double quotes.
"This is a string literal in Swift"
In some programming languages you can use single quotes to create a string literal. This is still not possible in Swift.
Once you have a string literal, it needs to be assigned to a constant or to a variable. If you don’t assign, the compiler will ignore the string literal.
Basic operations with strings
// assignment to a constant let const = "This is a string literal in Swift" // assignment to a variable var str = "This is a string literal in Swift" // printing the variable print(str) // get the number of characters print(str.count) // get the type of variable print(type(of: str)) // appending to a variable str.append(".") // printing the new number of characters print(str.count) // final variable print print(str)
This is a string literal in Swift 33 String 34 This is a string literal in Swift.
This code shows basic operations of assignment, printing, counting, and appending a string variable.
Don’t forget that Swift is very opinionated and requires named parameter
of:when getting the type.
This will work:
print(type(of: str)) // works
This will not work:
print(type(str)) // not working
In our case we assigned string literal to a variable
var str = "This is a string literal in Swift"
Similarly we could assign a string literal to a constant, but then we could not
append the constant.
// just for assign let const = "This is a string literal in Swift"
If you try to append a value to a String constant you will get the error:
const.append(".") //error: cannot use mutating member on immutable value //note: change 'let' to 'var' to make it mutable
We already concatenated stings using the
append method, however, concatenation is also possible using the addition operator (
let immutable_question = "How" + " are " + "you?"
In Swift, strings can be changed if you declare them with
var. However, if you declare a string to be a constant (keyword
let), then it cannot be changed.
The following special characters can be used to append to a String variable.
|\r||Carriage return character|
|\”||Double quotation mark|
|\’||Single quotation mark|
Double quotation mark helps writing a double quote inside a string literal without closing the literal.
let force = "He said: \"May the Force be with you\"." print(force)
He said: "May the Force be with you".
Frequently you concatenate a newline to a string literal as follows:
let output = "123 Street" + "\n"
Concatenation works only for the String type. It is why we need String interpolation if we plan to add some other literal type such as Int.
let output = "123 Street" + 3 // error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'
String interpolation is the process of inserting string literals or other data into an existing string literal.
The syntax for string interpolation is a backslash followed by a set of parentheses –
Anything inserted inside the parentheses are interpolated into the existing string literal.
let pens = 3 let out = "I have \(pens) pens." print(out)
I have 3 pens.
With string interpolation you can combine different data types to generate new string literals.
let str = "The year is \(2014) and Swift is at version \(1.2)"
The length of a String
We already mentioned the
var str = "This is a string literal in Swift" print(str.count)
However, this works in Swift 4+ and 5+
Swift 2 and Swift 3 would use
Swift 1 used the global method
Split a string into an array
Split a string by single delimiter
let line = "We will explode the Swift string"; let res1 = line.split(separator: " ") let res2 = line.split(separator: "e") print(res1, res2)
["We", "will", "explode", "the", "Swift", "string"] ["W", " will ", "xplod", " th", " Swift string"]
One another consideration is needed. What if we have multiple white spaces and we would like to split with the white space as separator?
Usually we ignore the white spaces, but there is an optional parameter
omittingEmptySubsequences. If we set that to
false the returned array will have empty space elements.
omittingEmptySubsequences is set to
let line = "I don't need white spaces I need words!" print(line.split(separator: " ")) print(line.split(separator: " ", omittingEmptySubsequences: false))
["I", "don\'t", "need", "white", "spaces", "I", "need", "words!"] ["I", "", "", "don\'t", "", "", "need", "white", "spaces", "I", "need", "words!"]
String splitting by multiple delimiters
split method works just for single character separator or delimiter.
To split by multiple delimiters we will use
components, from the
import Foundation let line = "Uh, smart explode Swift string"; let res = line.components(separatedBy: CharacterSet(charactersIn: "aeiou")) print(res)
["Uh, sm", "rt ", "xpl", "d", " Sw", "ft str", "ng"]
String splitting by word delimiter
import Foundation let line = "We program in Swift!" let splits = line.components(separatedBy: "in") print(splits)
["We program ", " Swift!"]
Code will break the line:
We program in Swift! and we will get two parts:
- “We program “
- ” Swift!”
String split by word when word is just a single character is also a valid option.
import Foundation let line = "We program in Swift!" let splits = line.components(separatedBy: "i") print(splits)
["We program ", "n Sw", "ft!"]
Join the string from array of strings (characters)
For this job in Swift you may use
joined method from Swift Standard Library.
let array = ["May", "the", "force", "be", "with", "you", "!"] let joined = array.joined(separator: " ") print(joined)
May the force be with you!
There is one interesting case to convert an array of characters to a string:
let chars: [Character] = ["J", "o", "i", "n"] var string = String(chars) print(string)
For this purpose,
joined method is not needed.
Reverse the string
In Swift 4 and later, there is
reversed collections method.
let str = "Reverse me!" var rev = String(str.reversed()) print(reversed)
Check if string contains the substring
One very useful thing operation in Swift would be to check if a substring is part of a string. For that Swift has the
import Foundation var force = "May the force be with you!" print(force.contains("Yoda")) print(force.contains("force"))
…tags: strings & category: swift