这是用Swift编写的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]中写这个内容?
答案 0 :(得分:1)
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 }
}
(注意:这假定文件格式正确,否则可能会崩溃。)
或者,使用writeToFile()
编写的NSArray
方法
数组作为属性列表(XML)文件:
(primesList as NSArray).writeToFile(filePath, atomically: false)
可以用
回读if let storedList = NSArray(contentsOfFile: filePath) as? [Int] {
primesList = storedList
}