NEW: Master Swift design patterns with my latest book! >>

How to get the lines in a string as an array

Written by Paul Hudson    @twostraws

Swift’s strings have their lines separated by the \n character, which is a line break on Unix operating systems. Using that plus the components(separatedBy:) method, you can get an array of all the lines in a string like this:

let lines = str.components(separatedBy: "\n")

If you intend to use that regularly, consider making an extension on String like this one:

extension String {
    var lines: [String] {
        return self.components(separatedBy: "\n")
    }
}

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Love Hacking with Swift?

Get all 40 projects in PDF and HTML: buy the Hacking with Swift book! It contains over 1300 pages of hands-on Swift coding, and will really help boost your iOS career

Click here to visit the Hacking with Swift store >>