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

前端 未结 9 718
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题