[swift-dev] Linux Swift API
Johannes Weiß
johannesweiss at apple.com
Tue Jan 31 10:42:08 CST 2017
Hi Roman,
> On 31 Jan 2017, at 15:51, Roman Pastushkov via swift-dev <swift-dev at swift.org> wrote:
>
> Hello everyone! Now i am trying (newbie) on Ubuntu Swift 3. I am trying to Read String from File Using FileHandle
>
> import Foundation
> let filemgr = FileManager.default
> let filepath1 = "/home/roman/test"
>
> let file: FileHandle? = FileHandle(forReadingAtPath: filepath1)
>
> if file == nil {
> print("File open failed")
> } else {
> let databuffer = file?.readDataToEndOfFile
> let String1 = String(databuffer, encoding: String.Encoding.utf8)
> file?.closeFile()
> print(String1)
> }
>
> But get error from compiler
> /home/roman/swift/Sources/main.swift:11:19: error: 'init' has been renamed to 'init(describing:)'
> let String1 = String(databuffer, encoding: String.Encoding.utf8)
> ^
> Swift.String:21:12: note: 'init' has been explicitly marked unavailable here
> public init<T>(_: T)
> ^
the error message is actually quite misleading. There are a few things that you need to correct:
you want the following constructor:
String(data: databuffer, encoding: String.Encoding.utf8)
^^^^^
also, readDataToEndOfFile is a method, so you'll need to call it (`file?.readDataToEndOfFile()`) and lastly, databuffer will then have the type Data? (aka Optional<Data>) so you might want to use a 'if let'. The working program could then look like this:
import Foundation
let filemgr = FileManager.default
let filepath1 = "/home/roman/test"
let file: FileHandle? = FileHandle(forReadingAtPath: filepath1)
if file == nil {
print("File open failed")
} else {
if let databuffer = file?.readDataToEndOfFile() {
let String1 = String(data: databuffer, encoding: String.Encoding.utf8)
file?.closeFile()
print("\(String1)")
} else {
print("File read failed")
}
}
HTH,
Johannes
More information about the swift-dev
mailing list