Hi Roman,

> On 31 Jan 2017, at 15:51, Roman Pastushkov via swift-dev 
> <swift-dev@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
_______________________________________________
swift-dev mailing list
swift-dev@swift.org
https://lists.swift.org/mailman/listinfo/swift-dev

Reply via email to