Read a File From Xcode Playgrounds

If you need to have some data in an external file and read it in playgrounds, here’s how to do it in Xcode 11.3 using Swift 5.1.

Put the file in the Resources directory of your playground.

Read it like this:

let path = Bundle.main.path(forResource: “input”, ofType: “txt”)!
let data = FileManager.default.contents(atPath: path)!
let contents = String(data: data, encoding: .utf8)!

print(contents)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.