0

我有 txt 文件的内容:

("All our dreams can come true, if we have the courage to pursue them.","Walt Disney")
("The secret of getting ahead is getting started","Mark Twain")

我想从中获取类型为 [(String, String)] 的元组数组。我尝试使用代码:

do {
    if let path = Bundle.main.path(forResource: "quotes", ofType: "txt"){
        let data = try String(contentsOfFile: path, encoding: .utf8)
        let arrayOfStrings = data.components(separatedBy: "\n")
        print(arrayOfStrings[0])
    }
} catch let err as NSError {
    // do something with Error
    print(err)
}

但是有了它,我无法获得元组值。如何使用 Swift 从 txt 文件中获取元组数组?

4

1 回答 1

1

正如 Larme 在评论中已经提到的,最好正确格式化您的文本。如果您无法更改文本格式,则需要手动解析其内容:

let data = """
("All our dreams can come true, if we have the courage to pursue them.","Walt Disney")
("The secret of getting ahead is getting started","Mark Twain")
"""

let tuples = data.split(whereSeparator: \.isNewline)
    .compactMap { line -> (Substring,Substring)? in
        let comps = line.components(separatedBy: #"",""#)
        guard comps.count == 2,
              let lhs = comps.first?.dropFirst(2),
              let rhs = comps.last?.dropLast(2) else { return nil }
        return (lhs,rhs)
    }

for tuple in tuples {
    print(tuple.0)
    print(tuple.1)
}

这将打印:

我们所有的梦想都可以实现,只要我们有勇气去追求它们。
沃尔特·迪斯尼
出人头地的秘诀是开始
马克·吐温

于 2021-03-10T17:57:15.343 回答