Swift Text File To Array of Strings

后端 未结 6 1363
逝去的感伤
逝去的感伤 2021-01-01 22:20

I was wondering what the simplest and cleanest to read a text file into an array of strings is in swift.

Text file:

line 1
line 2
line 3 
line 4
         


        
6条回答
  •  無奈伤痛
    2021-01-01 22:53

    Updated for Swift 3

        var arrayOfStrings: [String]?
    
        do {
            // This solution assumes  you've got the file in your bundle
            if let path = Bundle.main.path(forResource: "YourTextFilename", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)                
                arrayOfStrings = data.components(separatedBy: "\n")
                print(arrayOfStrings)
            }
        } catch let err as NSError {
            // do something with Error
            print(err)
        }
    

提交回复
热议问题