Swift文本文件到字符串数组

d7v8vwbk  于 2023-06-21  发布在  Swift
关注(0)|答案(7)|浏览(143)

我想知道在swift中将文本文件读入字符串数组中最简单和最干净的方法是什么。
文本文件:

line 1
line 2
line 3 
line 4

转换成这样的数组:

var array = ["line 1","line 2","line 3","line 4"]

我也想知道如何在struct中做类似的事情:

Struct struct{
   var name: String!
   var email: String!
}

因此,获取一个文本文件并将其放入数组结构中。
谢谢你的帮助!

byqmnocz

byqmnocz1#

首先,您必须阅读文件:

let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil)

然后使用componentsSeparatedByString方法将其按行分隔:

let lines : [String] = text.componentsSeparatedByString("\n")
ht4b089n

ht4b089n2#

更新为Swift 3

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)
    }
92vpleto

92vpleto3#

    • Swift 5更新:**

const路径包含文件路径。

do {
    let path: String = "file.txt"
    let file = try String(contentsOfFile: path)
    let text: [String] = file.components(separatedBy: "\n")
} catch let error {
    Swift.print("Fatal Error: \(error.localizedDescription)")
}

如果你想逐行打印file.txt里面的内容:

for line in text {
    Swift.print(line)
}
jhiyze9q

jhiyze9q4#

下面是一个将字符串转换为数组的方法(一旦你读到文本):

var myString = "Here is my string"

var myArray : [String] = myString.componentsSeparatedByString(" ")

这将返回具有以下值的字符串数组:["Here", "is", "my", "string"]

daupos2t

daupos2t5#

Swift 4:

do {
    let contents = try String(contentsOfFile: file, encoding: String.Encoding.utf8)
    let lines : [String] = contents.components(separatedBy: "\n")    
} catch let error as NSError {
    print(error.localizedDescription)
}
vd2z7a6w

vd2z7a6w6#

在Swift 3中,我的工作方式如下:

Import Foundation

let lines : [String] = contents.components(separatedBy: "\n")
rhfm7lfc

rhfm7lfc7#

已更新,无需硬编码文件路径:

因为Xcode要求你在一个项目中使用唯一的文件名,我们可以简单地在主包中搜索文件名。这种方法消除了对文件路径进行硬编码的需要,从而防止了潜在的问题,特别是在与其他人协作/在不同的机器上工作时:

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")

相关问题