What are strings in Swift?
A string is a data type where the data is made up of characters. For example: “a”, “b”, “3”, “Hello World”, “John”, etc. Swift strings are represented by the String type.
How to initialize strings
The following code shows all the different ways to initialize strings in Swift. To initialize a multi-line string, we use three double-quotation marks (“””) at the start and end of the string.
import Swiftlet name: String = "John"print(name)let myString = "Hello World!"print(myString)var newString = ""newString = "Another sample string"print(newString)let multiLineString = """Yet anotherstring that is initializedon multiple lines"""print(multiLineString)
How to access individual characters
Unlike other programming languages, Swift does not allow array like indexing to access individual characters in a string. Instead, it has a more complex and potentially safer way to access and modify characters in a string using built-in functions. The code is shown below:
import Swiftlet myString = "Hello World"let firstChar = myString.index(myString.startIndex, offsetBy: 0)let secChar = myString.index(myString.startIndex, offsetBy: 1)let secondChar = myString.index(after: myString.startIndex)print(myString[firstChar])print(myString[secChar])print(myString[secondChar])print("\n Accessing each character in the string \n")for character in myString {print(character)}
String Operations
1. Joining two strings
The following code demonstrates how to join two strings:
import Swiftvar s1 = "Hello "var s2 = " World!"// using the append() methods1.append(s2)print(s1)var string1 = "Hello "var string2 = " World!"var fin = string1 + string2print(fin)//using =+ operatorstring1 += string2print(string1)
2. Getting substrings
The following code demonstrates how to extract a substring from a larger string:
import Swiftlet s1 = "Hello World!"let index = s1.firstIndex(of: " ")!let firstWord = s1[..<index]print(firstWord)
3. Getting the length of a string
Swift has a built-in count property of each string that holds the length of the string:
import Swiftlet s1 = "Hello World!"print(s1.count)
There are some other functions available in the string struct such as:
lowercase(),uppercased(),isEmpty, and many others that help us with string manipulation.