在Swift 3中将字符串转换为整数数组?

时间:2017-06-04 03:37:56

标签: swift

我试图在文件中写一个数字数组。读完后,结果是一个字符串,我想知道如何读取数字数组或将字符串转换为数字数组?

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转换为数组?

1 个答案:

答案 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) }