我试图在文件中写一个数字数组。读完后,结果是一个字符串,我想知道如何读取数字数组或将字符串转换为数字数组?
let file = "sample.txt"
var arr1 = [Int]()
arr1 += 1...100
var text = String(describing: arr1)
var text1 : String = String()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
// writing
do {
try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
//reading
do {
text1 = try String(contentsOf: path, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
现在问题是如何将text1
转换为数组?
答案 0 :(得分:1)
问题是:如果您想保存 Int
数组,为什么要写一个 String
?
保存Int
数组的最简单方法是属性列表格式。
虽然Swift中推荐的方法是PropertyListSerialization
类,但它通过将Swift Int
桥接到Array
来编写和读取NSArray
数组。
let file = "sample.plist"
let arrayToWrite = [Int](1...100)
var arrayToRead = [Int]()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let url = dir.appendingPathComponent(file)
// writing
(arrayToWrite as NSArray).write(to: url, atomically: false)
//reading
arrayToRead = NSArray(contentsOf: url) as! [Int]
print(arrayToRead)
}
使用PropertyListSerialization
的 swiftier 方式是
// writing
do {
let data = try PropertyListSerialization.data(fromPropertyList: arrayToWrite, format: .binary, options: 0)
try data.write(to: url, options: .atomic)
}
catch { print(error) }
//reading
do {
let data = try Data(contentsOf: url)
arrayToRead = try PropertyListSerialization.propertyList(from: data, format: nil) as! [Int]
print(arrayToRead)
}
catch { print(error) }