To get a substring or a part of a string in Swift you can use prefix and suffix.
Here is an example if we wanted to get only the first 2 characters of a string using prefix
.
let str = "ABCD"
print(str.prefix(2))
// AB
To get the last 2 characters of a string using suffix
:
let str = "ABCD"
print(str.suffix(2))
// CD
What if you want to get a part of a string that’s in the middle?
You can use the array index notation to do this on a string:
let str = "ABCD"
let start = str.index(str.startIndex, offsetBy: 1)
let end = str.index(str.startIndex, offsetBy: 2)
let range = start...end
let newString = String(str[range])
print(newString)
// BC
To get one character of the string you can convert the string into an array:
let str = "ABCD"
var someChar = Array(str)[2]
print(firstChar)
This workaround is valid for most cases when you have a UTF8 or ASCII encoded string.
You can also use the index method provided above.
Use the contains
method to check if a substring exists:
import Foundation
let str = "ABCD"
print(str.contains("CD"))
Remember to import Foundation
or else this won’t work!
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.