How To Split A String In Swift With Examples

Splitting strings are needed in a lot of iOS applications.

How to split a string in Swift? Swift strings comes in with a built-in method called components that will split a string into an array. It can split a string by space, but also by any character set you need.

There are many reasons why you’d want to split a string in Swift. This article will dive into some of the use cases.

How to split a string in Swift with examples

Let’s say you want to split a string up by spaces. For example, you want to change the string “Apple Orange” to an array where array[0] = “Apple” and array[1] = “Orange”. This is simple to do using the components method of Swift strings.

var str = "Orange Apple"
var strArray = str.components(separatedBy: " ")

print(strArray[0])
print(strArray[1])

If you wanted to say split a string up by the dashes, for example “Banana-Kiwi”, you could use the following example code:

var str = "Banana-Kiwi"
var strArray = str.components(separatedBy: "-")

Splitting strings by a certain character is simple and easy to use. You can even use two or more characters as the separatedBy parameter. For example, we can split the string “iPhone > iPad > MacBook” by the characters ” > “. This ensures the white space is removed.

var str = "iPhone > iPad > Macbook"
var strArray = str.components(separatedBy: " > ")

print(strArray[0]) // Prints iPhone
print(strArray[1]) // Prints iPad
print(strArray[2]) // Prints Macbook

Split a full name by first and last name in Swift

Splitting a users name is a common problem. You can just use the simple components method to split it up by space and that works fine.

For example, to split “Eddy Chung” into two parts, you could do the following:

var str = "Eddy Chung"
var strArray = str.components(separatedBy: " ")

print(strArray[0]) // Prints Eddy
print(strArray[1]) // Prints Chung

However, if you want to split a more complicated name up, I’d recommend using the PersonNameComponentsFormatter, this is useful when you have a more complicated name such as “Mr. Eddy Edward Chung Jr.”. Here’s a code example showing you how to do that.

let nameFormatter = PersonNameComponentsFormatter()
let name =  "Mr. Eddy Edward Chung Jr"
if let nameComps  = nameFormatter.personNameComponents(from: name) {
    nameComps.namePrefix   // Mr.
    nameComps.givenName    // Eddy
    nameComps.middleName   // Edward
    nameComps.familyName   // Chung
    nameComps.nameSuffix   // Jr.

    nameFormatter.style = .default
    print(nameFormatter.string(from: nameComps))   // "Eddy Chung"

    nameFormatter.style = .short
    print(nameFormatter.string(from: nameComps))   // "Eddy"

    nameFormatter.style = .long
    print(nameFormatter.string(from: nameComps))   // "Mr. Eddy Edward Chung Jr"

    nameFormatter.style = .abbreviated
    print(nameFormatter.string(from: nameComps))   // EC
}

Person components requires iOS 10 or later. It’s a great way to break up a more complicated name. Some apps that require identify verification or are finance industry will benefit greatly from using this built in feature.

Split CSV file or comma separated string in Swift

Reading in a comma split values file is a common task required in programming. Typically CSV values consists of columns of values separated by commas and rows separated by new line characters.

In Swift, we can write a simple one-liner that will parse this into a two-dimensional array. Here’s the code:

import Foundation
let content = "eddy,chung,loves,swift\nsecond,line,of, text" //string with CSV file content
let parsedCSV: [[String]] = content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") }

print(parsedCSV) // Prints [["eddy", "chung", "loves", "swift"], ["second", "line", "of", " text"]]"

The code above should be sufficient for most CSV parsing problems. You can also use third party libraries on Github. Here is a couple of resources to take a look at:

Split string by a new line or tab in Swift

Splitting by a new line in Swift is super simple. We just need to put the parameter to the components method as “\n”. Here is a code example:

import Foundation
let content = "first line!\n second line!" //string with new line character
let arrayOfContent = content.components(separatedBy: "\n")

print(arrayOfContent)

Split by new line

Splitting by tabs in Swift is also easy to do. Just put “\t” as the separatedBy parameter in the components call. Here is a code example:

import Foundation
let content = "before TAB!\t after TAB!" //string with tab
let arrayOfContent = content.components(separatedBy: "\t")

print(arrayOfContent)

Split up string by tab

What if you want to split up strings by tabs OR spaces? To split a string based on multiple characters, we need to create a character set. For this example, we’ll use a character set that includes “\n” and “\t”. Here is the code.

import Foundation
let content = "before TAB!\t after TAB! \nSecond Line!" //string with tab & new line
let arrayOfContent = content.components(separatedBy: CharacterSet(["\t", "\n"]))

print(arrayOfContent)

Split by new lines or tabs

How to split swift string based on whitespace or new lines? So if you’d like to split the string based on any kind of whitespace or new lines, Swift has a built-in character set for this purpose. Its named whitespacesAndNewlines appropriately. You can also just split by whitespaces. Here is the code example to do this operation:

import Foundation
let content = "before TAB!\t after TAB! \nSecond Line!"
let arrayOfContent = content.components(separatedBy: .whitespacesAndNewlines)

print(arrayOfContent)

Splitting and parsing date string in Swift

Parsing and splitting date strings in Swift code is a very common problem developers face. Dates can be stored in a number of different ways depending on how you’re housing your data. Dates can also be returned by APIs you have no control over.

Because of all the different formats dates can come in, Swift has some tools built-in to make handling all these different cases easier. The DateFormatter class covers most common use cases for date string handling.

ISO 8601 Format

ISO 8601 format is an international standard for representing dates and time-related data. The purpose of this standard was to eliminate ambiguity when communicating about dates or time data. This standard was first published in 1988 and used by many different databases.

To parse this date string that looks like this in Swift

2015-01-01T00:00:00.000Z

We can create an extension to our date class like so:

extension Date {
    static func ISOStringFromDate(date: Date) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

        return dateFormatter.string(from: date).appending("Z")
    }

    static func dateFromISOString(string: String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone.autoupdatingCurrent
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

        return dateFormatter.date(from: string)
    }
}

Note that in iOS 10+, ISO 8601 is built-in formatter. We can use it like so:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
view rawbuiltiniso.swift hosted with ❤ by GitHub
International Format
The international date format year-month-day is very popular. How to convert an international date format string to date in Swift code:

var dateString = "2018-12-15"
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.date(from: dateString)
print(date!)

The international date format is one of the most popular ways of representing dates. This is something you will work with often if your app involves any type of scheduling.

American Format

The American format of dates is often the cause of much confusion for a lot of developers not from America. It is month/day/year which is the same way most English speakers say their dates in spoken word.

To parse this date, we use the date format “MM/dd/yyyy“. Here is the code example:

var dateString = "01/05/2019"
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
var date = dateFormatter.date(from: dateString)
print(date!)

Additional date resources

Parsing dates is a common problem for iOS developers to face. Here are two websites that contain additional information for this topic:

How do I remove certain characters from a Swift string? Use the built-in method replacingOccurrences. For example stringd.replacingOccurrences(of: “d”, with: “”)

How do I make a Swift string uppercase? Call upperCased() on the string. For example lowerCaseString.upperCased()

How do I make a Swift string lowercase? Call lowerCased() on the string. For example upperCaseString.lowerCased()

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts