Updated so you don't need to hardcode the file path:
Because Xcode requires you to use unique filenames inside a project, we can simply search for the filename inside the main bundle. This approach eliminates the need to hardcode the file path, thereby preventing potential issues, especially when collaborating with others / working on different machines:
import Foundation
extension Bundle {
/// Creates an array of strings from a text file in the bundle.
/// - Parameters:
/// - fileName: The name of the text file.
/// - separatedBy: The string used to separate the contents of the file.
/// - Returns: An array of strings representing the contents of the file, separated by the specified separator.
/// - Note: Will raise a fatal error if the file cannot be located in the bundle or if the file cannot be decoded as a String.
func createArrayOfStringsFromTextFile(fileName file: String, separatedBy separator: String) -> [String] {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate '\(file)' in bundle.")
}
guard let fileContent = try? String(contentsOf: url) else {
fatalError("Failed to read content of '\(file)' as a string.")
}
let result: [String] = fileContent.components(separatedBy: separator)
return result
}
}
Usage:
let result: [String] = Bundle.main.createArrayOfStringsFromTextFile(fileName: "someFile.txt", separatedBy: "\n")