var arrayOfStrings: [String]?
do {
// This solution assumes you've got the file in your bundle
if let path = Bundle.main.path(forResource: "YourTextFilename", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
arrayOfStrings = data.components(separatedBy: "\n")
print(arrayOfStrings)
}
} catch let err as NSError {
// do something with Error
print(err)
}
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
}
}
用途:
let result: [String] = Bundle.main.createArrayOfStringsFromTextFile(fileName: "someFile.txt", separatedBy: "\n")
7条答案
按热度按时间byqmnocz1#
首先,您必须阅读文件:
然后使用
componentsSeparatedByString
方法将其按行分隔:ht4b089n2#
更新为Swift 3
92vpleto3#
const路径包含文件路径。
如果你想逐行打印
file.txt
里面的内容:jhiyze9q4#
下面是一个将字符串转换为数组的方法(一旦你读到文本):
这将返回具有以下值的字符串数组:
["Here", "is", "my", "string"]
daupos2t5#
Swift 4:
vd2z7a6w6#
在Swift 3中,我的工作方式如下:
rhfm7lfc7#
已更新,无需硬编码文件路径:
因为Xcode要求你在一个项目中使用唯一的文件名,我们可以简单地在主包中搜索文件名。这种方法消除了对文件路径进行硬编码的需要,从而防止了潜在的问题,特别是在与其他人协作/在不同的机器上工作时:
用途: