Import a Text File into Swift Playgrounds

I have been using Playgrounds quite a bit recently to practice solving algorithms. I like that it has a simpler interface than a regular XCode project which is perfect for single-scope algorithms. The bar on the right side that displays results of functions and variables before returning or printing them is especially helpful. Keeping large datasets out of the playground file allows it to run faster. Here is an easy way to add and use a text file in your Swift Playground.

Start with a text file. I have a textfile called Baseball-teams that has a list of baseball teams in the MLB.

Screen Shot 2016-11-17 at 10.19.22 AM.png

Open a Swift Playground file.

Screen Shot 2016-11-17 at 10.22.46 AM.png

I named mine Baseball.

Screen Shot 2016-11-17 at 10.23.21 AM.png

Now you need to add the text file as a resource. Hit Command  1.

Screen Shot 2016-11-17 at 10.25.54 AM.png

The Baseball-Teams.txt files will go into Resources. You can either drag and drop it into the folder or go to File > Add Files to “Resources”.

Screen Shot 2016-11-17 at 10.27.09 AM.png

Now it’s time to access the data. Create a variable called fileURL.

let fileURL = Bundle.main.url(forResource: “Baseball-Teams”, withExtension: “txt”)

Note: this was once urlForResource, but has been simplified in the last update of Swift. Now create another variable called baseballTeams.

let baseballTeams = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)

At this point you will see the date on the righthand bar, but I printed the data as well.

Screen Shot 2016-11-17 at 10.40.22 AM.png

Great! A really long String! I added this function to reformat the String into an Array.

let baseballTeamArray = baseballTeams.components(separatedBy: NSCharacterSet.newlines)

Screen Shot 2016-11-17 at 10.48.38 AM.png

Pro Tip: If you are unsure about the type, use Option + Click on the name of the variable and Playground will show it.

Screen Shot 2016-11-17 at 10.51.46 AM.png.

And that’s it! Now you are on your way to working with the data from a text file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s