A
A
AnD2018-08-17 13:40:51
iOS
AnD, 2018-08-17 13:40:51

How to read data from a file?

how to read data from txt file line by line?
that is, let's say there are lines in the file:
1 - although
2 - always
3 - to amaze,
I want that the first time the function is called, a line is randomly selected from the file (let's say 3 first) and it is displayed on the screen
later, the next time it is called, the same way the next line was randomly selected (let's say 1), etc.
perhaps somewhere you can read about it.
and it may be more convenient to store strings in some other format.
tell.
I will be grateful for the answer.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Globak, 2018-08-18
@AnDVa

You can go two ways, use files, json or .plist is the most convenient, or use entire databases, such as SQL or Realm for example.
For the first plot, the files are usually fully loaded into RAM (completely read) and converted into a standard structure such as a dictionary or array. In this case, you yourself use the language methods to get a random value.
How to read files can be found here stackoverflow.com
But with the second option, in my opinion, it is more convenient to work, but more difficult to integrate, there you already push all the data into the database, and in the application you connect to the database and use the database to get random values. If you have large data, then it is better to use the second option, but for simplicity, it is better to use the first option.

B
briahas, 2018-08-20
@briahas

Reading a file or-or

  1. let fileManager = FileManager()
    let data = fileManager.contents(atPath: url.path)</li>

  2. do {
       let data = try String(contentsOf: url)
    } catch {
        print(error)
    }

    Then you hit on the lines and randomly choose some.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question