gpt4 book ai didi

swift - 如何从文件中读取并放入数组

转载 作者:行者123 更新时间:2023-11-28 07:13:21 25 4
gpt4 key购买 nike

这是一个用 Swift 编写的 Sieve of Eratosthenes 应用程序。我可以将输出写入文件,但我只能通过手动传递 [primesList] 开始。相反,我想读取文件 primesList.txt 并将其放入 [primesList]。

import Foundation

// set a file called test.txt on Desktop to be used by this program
let dir = "~/Desktop"
let file = "primesList.txt"
let path = dir.stringByExpandingTildeInPath
let filePath: NSString = path.stringByAppendingPathComponent(file)

// set some needed variables and constants
var highestNumberEvaluated = 100
var primesList = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

let readFromFile = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
println(readFromFile)

let inputNumber = 100
let range2Evaluate = 100
let last2Evaluate = inputNumber + range2Evaluate

println("Find primes between \(inputNumber) and \(last2Evaluate):\n")

// create a dictionary of numbers to be evaluated true or false
var numbersList = [Int: Bool]()
for i in inputNumber...last2Evaluate {
numbersList[i] = true
}

// mark as not prime (false) all not primes in numbersList
for i in primesList {
if i < Int(sqrt(Double(last2Evaluate))) {
let myMultiplier = inputNumber / i
var bottomValue = i * myMultiplier
for var j = bottomValue; j < (bottomValue + range2Evaluate + 2); j += i {
numbersList[j] = false
}
} else {break}
}

// create an array made by all primes found true, then sort
var primesFoundList = [Int]()
for (myKey, myValue) in numbersList {
if myValue == true {
primesFoundList.append(myKey)
}
}
primesFoundList.sort { $0 < $1 }

// add the primes found to the original primes list and write on the file test.txt
primesList += primesFoundList
let toBeWritten = toString(primesList)
toBeWritten.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)

在第13-14行我可以得到文件的内容,我如何将这些内容写到数组[primesList]中?

最佳答案

toString() 函数不太适合生成要被再读一遍。您可以使用

创建一个简单的逗号分隔列表
let toBeWritten = ", ".join(primesList.map { String($0)})
toBeWritten.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)

可以用

再次阅读
if let readFromFile = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) {
primesList = readFromFile.componentsSeparatedByString(",").map() { ($0 as NSString).integerValue }
}

(注意:这假定文件具有正确的格式,否则可能会崩溃。)

或者,使用 NSArray 中的 writeToFile() 方法写入数组作为属性列表 (XML) 文件:

(primesList as NSArray).writeToFile(filePath, atomically: false)

可以读回

if let storedList = NSArray(contentsOfFile: filePath) as? [Int] {
primesList = storedList
}

关于swift - 如何从文件中读取并放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27530848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com