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.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

Click here to visit the Hacking with Swift store >>