Swift 2.2 Linux - open file for reading

(edited to display Swift 1 and Swift 2 code)

I am trying to read a small text file using Swift 2.2 on Linux (snapshot December 22).
Mint 14.04 and Ubuntu 15.10 give identical results.
If there is any way to read from a text file, respond.

Swift 2 Source:

let text = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
print(text)

Mistake:

prefix.swift:18:13: error: type 'String' has no member 'stringWithContentsOfFile'
let text = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
           ^~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~

Source Swift 1:

import Foundation
let text = NSString(contentsOfFile: "foo.txt", encoding: NSASCIIStringEncoding, error: nil)
print(text)

Mistake:

prefix.swift:14:12: error: argument labels '(contentsOfFile:, encoding:, error:)' do not match any available overloads
let text = NSString(contentsOfFile: "foo.txt", encoding: NSASCIIStringEncoding, error: nil)
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prefix.swift:14:12: note: overloads for 'NSString' exist with these partially matching parameter lists: (charactersNoCopy: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone: Bool), (format: String, locale: AnyObject?, arguments: CVaListPointer), (bytes: UnsafePointer<Void>, length: Int, encoding: UInt)
var text = NSString(contentsOfFile: "foo.txt", encoding: NSASCIIStringEncoding, error: nil)
           ^
+4
source share
3 answers

NSString is not yet fully implemented for the cross-platform version of the Foundation framework. Here you can track the status of various parts of the fund: Status Status

+2
source

Glibc, ​​

import Glibc

let path = "./sample.txt"
let BUFSIZE = 1024

let fp = fopen(path, "r")
if fp != nil {
  var buf = [CChar](count:BUFSIZE, repeatedValue:CChar(0))
  while fgets(&buf, Int32(BUFSIZE), fp) != nil {
    print(String.fromCString(buf)!, terminator:"")
  }
}
+2

try this on Linux Swift 2.2 (snapshot January 11, 2016 using the Foundation module) https://swift.org/download/#older-snapshots

import Foundation
...
let path = "./sample.txt"
if let text = try? NSString(contentsOfFile: path as String, encoding: NSUTF8StringEncoding).bridge() {  // use .bridge() to convert to String, see https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md#known-issues
    print(text)
}
0
source

Source: https://habr.com/ru/post/1620178/


All Articles