0

I'm trying to write an array of numbers in a file. After reading it, the result is a string, I'm wondering how to read an array of numbers or transform the string into array of numbers?

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 */}
}

Now the question is how can I transform text1 into an array of numbers?

1
  • 2
    you mean convert a string to an array of integers? Try splitting to list of strings, then convert every array item to int (Google it) Commented Jun 4, 2017 at 3:40

1 Answer 1

1

The question is: if you want to save an array of Int why do write and read a String?

The easiest way to save an array of Int is the property list format.

Although the recommended way in Swift is the PropertyListSerialization class this writes and reads an array of Int by bridging the Swift Array to 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)
}

The swiftier way using PropertyListSerialization is

// 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) }
Sign up to request clarification or add additional context in comments.

1 Comment

May be JSONSerialization is another possibility how to do it easy and the "right way".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.