Blog Detail

Swift Strings

23 Feb 15
Steven Beyers
, , ,
No Comments
If you have been using Swift over the past few months, chances are you have come across issues using Strings. Many of the Objective-C methods we have relied on no longer work without some extra leg work. Over the last few days I have seen several questions posed on blogs and forums asking how to complete certain tasks with Swift’s Strings. Some of the answers I have seen work, but really aren’t the best answers. Here is, in my opinion, the best way to handle a few of the scenarios I have seen multiple times.

TL;DR;

Use the methods hasPrefix(), hasSuffix() and rangeOfString() and create a category for convenient re-use.

Begins With/Ends With

I have seen many people asking in forums how to check if a String begins or ends with another String. This is very simple and is exactly the same as we would have done in Objective-C.

Contains String 

Background

Before I dive into code I want to acknowledge that the Sift docs state:

Swift’s String type is bridged seamlessly to Foundation’s  NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire  NSString API is available to call on any  String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.

This would seem to indicate that we can use methods similar to how we would have in Objective-C such as

but this simply doesn’t work. There are a few ways to go about solving this issue.

Solution #1 – Bridge to Objective-C

The first option is to bridge to Objective-C and use an NSString object which would then allow us to use the containsString() method.

This method works just fine and doesn’t look too bad. However, there is another method if you want to avoid casting to NSString every time you need to run this operation.

Solution #2 – My Preferred Solution

A pure Swift way of doing this is to use the rangeOfString() method as you can see here:

This is clearly a lot more code than solution #1 so you may be curious why I would prefer this solution. To start with, as I already stated, this is pure Swift and I do not have to do any type casting. Second, I would never write this code more than one time. Instead, I would create a String extension and put this code in that extension. If, in the extension, I use the function signature

That will give me the ability to re-use the rangeOfString method on any String object. Now all I have to write when I need to check for a substring is

which is exactly what we wanted to be able to use in the first place!