Updated for Swift 4
Checking the beginning of the line and ends with
You can use the hasPrefix(_:) and hasSuffix(_:) methods to check for equality with another string.
let str = "Hello, playground" if str.hasPrefix("Hello") { // true print("Prefix exists") } if str.hasSuffix("ground") { // true print("Suffix exists") }
Getting the actual prefix and suffix substrings
To get the actual prefix or suffix substring, you can use one of the following methods. I recommend the first method of simplicity for him. All methods use str as
let str = "Hello, playground"
Method 1: (recommended) prefix(Int) and suffix(Int)
let prefix = String(str.prefix(5))
This is the best method in my opinion. Unlike methods 2 and 3 below, this method will not crash if the indexes go beyond. It will simply return all characters in the string.
let prefix = String(str.prefix(225))
Of course, sometimes crashes are good because they tell you that there is a problem with your code. Therefore, consider the second method below. It throws an error if the index goes out of bounds.
Method 2: prefix(upto:) and suffix(from:)
Swift String indices are complex because they must consider special characters (e.g. emoji). However, once you get the index, it's easy to get a prefix or suffix. (See my other answer on String.Index .)
let prefixIndex = str.index(str.startIndex, offsetBy: 5) let prefix = String(str.prefix(upTo: prefixIndex)) // Hello let suffixIndex = str.index(str.endIndex, offsetBy: -6) let suffix = String(str.suffix(from: suffixIndex)) // ground
If you want to protect against going beyond, you can make an index using limitedBy (again, see this answer ).
Method 3: Indexes
Since String is a collection, you can use indexes to get the prefix and suffix.
let prefixIndex = str.index(str.startIndex, offsetBy: 5) let prefix = String(str[..<prefixIndex]) // Hello let suffixIndex = str.index(str.endIndex, offsetBy: -6) let suffix = String(str[suffixIndex...]) // ground
additional literature