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.
Open a Swift Playground file.
I named mine Baseball.
Now you need to add the text file as a resource. Hit Command 1.
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”.
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.
Great! A really long String! I added this function to reformat the String into an Array.
let baseballTeamArray = baseballTeams.components(separatedBy: NSCharacterSet.newlines)
Pro Tip: If you are unsure about the type, use Option + Click on the name of the variable and Playground will show it.
And that’s it! Now you are on your way to working with the data from a text file.
Leave a Reply