How do I load a text file line by line into an array with Swift?

前端 未结 9 716
盖世英雄少女心
盖世英雄少女心 2020-12-29 18:51

How do I load a text file line by line into an array with swift?

相关标签:
9条回答
  • 2020-12-29 19:46

    This works only until Xcode 6.1 beta 1. In 6.1 beta 2 you must write this:

    var err: NSError? = NSError()
    let s = String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding, error: &err)
    

    Where fullPath is a string containing the full path to the file and NSUTF8StringEncoding is a predefined constant for UTF8-Encoding.

    You can also use NSMacOSRomanStringEncoding for Mac files or NSISOLatin1StringEncoding for Windows files.

    s is an optional String and you can look if reading the file was successful:

    if (s != nil)
    {
        return (s!) // Return the string as "normal" string, not as optional string
    }
    
    0 讨论(0)
  • 2020-12-29 19:47

    Something along the lines of:

    func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
        guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") else {
            return nil
        }
    
        do {
            let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
            return content.componentsSeparatedByString("\n")
        } catch _ as NSError {
            return nil
        }
    }
    

    This approach assumes the file in question is located in your app bundle.

    0 讨论(0)
  • 2020-12-29 19:52

    If you are in Swift 2.0, you should use:

    let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
    if path == nil {
      return nil
    }
    
    var fileContents: String? = nil
    do {
      fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
    } catch _ as NSError {
      return nil
    }
    
    0 讨论(0)
提交回复
热议问题