简体   繁体   中英

Text file to array in swift

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 = ["word1", "word2", "word3"]. Here is my current code I got from bit.ly/39IC642

let path = Bundle.main.path(forResource: "words_alpha", ofType: "txt") // file path for file "words_alpha.txt"
let string = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)

I am getting this error: Cannot use instance member 'path' within property initializer; property initializers run before 'self' is available

I am fairly new to using Swift and coding in general, please be detailed with your answers. Thank you!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM