Linux Swift API


(Roman Pastushkov) #1

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)
           ^
<unknown>:0: error: build had 1 command failures
error: exit(1): /home/roman/swift-3.0.2-RELEASE-ubuntu16.04/usr/bin/swift-build-tool -f /home/roman/swift/.build/debug.yaml

Why it talking about init? when i use String

Roman Pastushkov
xnucleargeminix@aol.com


(Johannes Weiss) #2

Hi Roman,

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

···

On 31 Jan 2017, at 15:51, Roman Pastushkov via swift-dev <swift-dev@swift.org> wrote: