Swift Text File To Array of Strings

后端 未结 6 1335
逝去的感伤
逝去的感伤 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:44

    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)
    }
    
    0 讨论(0)
  • 2021-01-01 22:46

    Updated for Swift 5:

    The const path contains the file path.

    do {
        let path: String = "file.txt"
        let file = try String(contentsOfFile: path)
        let text: [String] = file.components(separatedBy: "\n")
    } catch let error {
        Swift.print("Fatal Error: \(error.localizedDescription)")
    }
    

    If you want to print what's inside of file.txt line by line:

    for line in text {
        Swift.print(line)
    }
    
    0 讨论(0)
  • 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)
        }
    
    0 讨论(0)
  • 2021-01-01 22:55

    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"]

    0 讨论(0)
  • 2021-01-01 23:03

    In Swift 3 for me worked like below:

    Import Foundation
    
    let lines : [String] = contents.components(separatedBy: "\n")
    
    0 讨论(0)
  • 2021-01-01 23:07

    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")
    
    0 讨论(0)
提交回复
热议问题