Working with Strings in Swift

In this post I’ll discuss replacing characters in a string, splitting a string using some value, and using regexes to count the number of matches in a string, and locating the first match in a string. I’m using XCode 6.4 with Swift 1.2. If you’re not sure which version of Swift you’re running, you can call the following from the command line,

$ xcrun swift --version
Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)
Target: x86_64-apple-darwin15.0.0

First Thing

I’m running this in a playground, and I’ve imported Cocoa at the first line,

import Cocoa

Replacing Characters

The following will replace and ", " sequences with "+". If it doesn’t find a ", " then str2 will simply be a copy of str1.

var str1 = "Hello, playground"
var str2 = str1.stringByReplacingOccurrencesOfString( ", ", withString: "+" )

Split a String

Splitting a string predictably returns an array of strings.

str1 = "Hallo, Welt"
var arr = str1.componentsSeparatedByString(", ")
str2 = join("*", arr)

# Search for a Substring #

This operation will return an `Integer`, so you don't have to worry about getting a `nil` if there are no matches.

var regex = NSRegularExpression( pattern:"\\*", options:nil, error:nil )
var match = regex!.numberOfMatchesInString( str2, options: nil, range: NSRange( location: 0, length: count(str2) ) )

Locate the First Match in a String

This operation returns a NSTextCheckingResult which is returned by the NSRegularExpression and NSDataDetector classes to indicate the discovery of content.

var fmatch = regex!.firstMatchInString( str2, options: nil, range: NSRange( location:0, length: count(str2) ) )
println( fmatch!.range.location )

At the end here, I've called the range attribute of the NSTextCheckingResult, which is an NSRange object, and then I accessed the location attribute of the NSRange object. For more information about NSRange, checkout NSHipster.

Leave a Reply

Your email address will not be published. Required fields are marked *