Hi, I am trying to read a file line by line. I am unable to get a clear answer from searching the web, so I appreciate your help. I'm exploring two possibilities, (1) use a cocoapod to read a file line by line, and (2) slurp the file into a String and split the string into lines.
(1) Does anyone know a cocoapod suitable for reading a file line by line? Or at least for reading all of a file, if not line by line?
(2) I tried to slurp the entire file into a string, with the intent to then work on splitting the whole content into lines. But I was unable to get through the first step. When I try String(contentsOfFile: "foo")
in the swift repl, I get an error:
1> String (contentsOfFile: "foo.txt")
error: repl.swift:1:1: error: argument labels '(contentsOfFile:)' do not match any available overloads
String (contentsOfFile: "foo.txt")
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition the repl prints out what it thinks are the allowed versions of String.init:
repl.swift:1:1: note: overloads for 'String' exist with these partially matching parameter lists:
(_StringGuts), (Character), (from: Decoder), (cString: UnsafePointer<CChar>),
(cString: UnsafePointer<UInt8>), (validatingUTF8: UnsafePointer<CChar>),
(String.CharacterView), (_builtinUnicodeScalarLiteral: Int32), (Unicode.Scalar),
(stringLiteral: String), (T), (_cocoaString: AnyObject), (stringInterpolation: String...),
(stringInterpolationSegment: T), (T, radix: Int, uppercase: Bool), (S),
(String, obsoletedInSwift4: ()), (String.UnicodeScalarView), (String.UTF16View),
(String.UTF8View), (Substring), (Substring.UTF8View), (Substring.UTF16View),
(Substring.UnicodeScalarView), (Substring.CharacterView), (describing: Subject),
(reflecting: Subject)
This list doesn't seem to have contentsOf
or contentsOfFile
or some others such as format
, which are mentioned in the documentation for the String class: Apple Developer Documentation
For the record I am working with swift 4.2 (Xcode 10.0) on macOS 10.13.6 High Sierra.
Can someone help me understand what's going on here? Why isn't contentsOf
or contentsOfFile
recognized? Is there another way to accomplish the goal of slurping an entire file into a String?
Thanks for your help, I appreciate it very much.
Robert Dodier