String Manipulations in Swift 4
First thing first, Swift 4’s API for String has been beefed up with many powerful capabilities. Strings and String manipulations are essentials for any or most solutions. Swift language offers some powerful way to do this. So let’s review some of the language capabilities.
To create a string, you can assign it to a property:

What if you want to repeat a string multiple times? You can use the repeating feature:

Sometimes you need to represent a multi-line string and this can be done easily with 3 opening quotes and 3 closing quotes. Each line in the multi-line string literal contains an end-of-line character \n.

To parse through each character in a String, you can do the following:

There are several ways to get the string portion or content between the two paragraph tags.

Let me explain what’s going on. The first approach above makes assumption that the <p></p> tags exist. So we use a fixed offset from the start and end of the string to extract the middle portion. On the other hand, we can use the second approach to determine the index based on identifiable parts of the <p></p> tags. Because we may not find the matching index, we default to using the start and end index of the original string. Which way do you prefer? Is there a better way of doing the same? Feel free to share it in the comments below.
Sometimes we may need to identify the position of the character in the string. How do we do this?

Note that we are advancing the offset by the position number from the String’s start index each time to retrieve the next character. Sometimes, you might only care about the position for “x” and “o” so you can use comparisons to only print those out. See the following example:

There are cases where you will need to deal with words instead of letters in the String. Below is an example of a function that takes a String and returns a titlecased String that respect some rules.

Let’s review what is happening with the above code.
- The title String is split by a blank space and a list of words is stored in the variable called words.
- The first in the title String will need to be capitalized regardless if it’s contained in the set of Strings that shouldn’t be capitalized.
- The words in the middle of the title are compared against the set of non-capitalizable words and append to the properCapitalization variable. You need to ensure that the comparison is done without case sensitive.
- The last word in the title String follows the same rule as comment 2.
Where to go from here?
String manipulations in Swift have come a long way. Check out the Apple documentation for more: Swift Standard Library Reference — String and post some of your favorite String manipulations in the comments below.
