Text file to array in swift

后端 未结 1 690
[愿得一人]
[愿得一人] 2021-01-26 07:00

I\'m trying to create a dictionary app on IOS. I have a text file (words_alpha.txt) in my Bundle, and I want to read all the words/lines, and place them into an arrray. String =

相关标签:
1条回答
  • 2021-01-26 07:57

    If you are writing an iOS app, you can move such initialization into viewDidLoad():

        var wordArray: [String] = []
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //...
            let url = Bundle.main.url(forResource: "words_alpha", withExtension: "txt")! // file URL for file "words_alpha.txt"
            do {
                let string = try String(contentsOf: url, encoding: .utf8)
                wordArray = string.components(separatedBy: CharacterSet.newlines)
            } catch {
                print(error)
            }
        }
    

    If your words_alpha.txt does contain multiple words per line, you may need some other way.

    0 讨论(0)
提交回复
热议问题