Swift Text File To Array of Strings

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

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 

Into an array like this:

var array = ["line 1","line 2","line 3","line 4"] 

I would also like to know how to do a similar thing into struct like this:

Struct struct{    var name: String!    var email: String! } 

so take a text file and put it into struct's in an array.

Thanks for the help!

回答1:

First you must read the file:

let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil) 

Then you separate it by line using the componentsSeparatedByString method:

let lines : [String] = text.componentsSeparatedByString("\n") 


回答2:

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)     } 


回答3:

Here is a way to convert a string to an array(Once you read in the text):

var myString = "Here is my string"  var myArray : [String] = myString.componentsSeparatedByString(" ") 

This returns a string array with the following values: ["Here", "is", "my", "string"]



回答4:

In Swift 3 for me worked like below:

Import Foundation  let lines : [String] = contents.components(separatedBy: "\n") 


回答5:

Swift 4:

do {         let contents = try String(contentsOfFile: file, encoding: String.Encoding.utf8)         let lines : [String] = contents.components(separatedBy: "\n")      } catch let error as NSError {         print(error.localizedDescription)     } 


回答6:

Updated for Swift 4:

do {     let file = try String(contentsOfFile: path!)     let text: [String] = file.components(separatedBy: "\n") } catch {     Swift.print("Fatal Error: Couldn't read the contents!") } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!