xcode - Swift - 读取文件

标签 xcode file swift

我在使用 swift 读取文件时遇到问题。我在网上搜索了很多,看是否能找到任何东西,我发现了 3 个不同的,但我无法让它们中的任何一个工作

他们在这里:

    import Foundation


//----- 1 ------
var error: NSErrorPointer = nil

let url = NSURL(string: "ISO.csv")
let csvString = String(contentsOfURL:url!, encoding: NSUTF8StringEncoding, error: error);


println("contest")
println(csvString)


//----- 2 ------
func readFile(fileName: String, fileType: String) -> String{
    var fileRoot = NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)
    var contents = NSString.stringWithContentsOfFile(fileRoot!, encoding: NSUTF8StringEncoding, error: nil)
    return contents
}

// example: read file.txt
var contents = readFile("ISO", "csv")
println(contents)


//----- 3 -----

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)

在数字 1 中:它只返回一个 nil。但它适用于从网站返回数据

数字 2:/ISO/main.swift:26:20: 'String.Type' 没有名为 'stringWithContentsOfFile' 的成员

数字 3 : /ISO/main.swift:38:21: 'stringWithContentsOfFile(_:encoding:error:)' 不可用:使用对象构造 'NSString(contentsOfFile:encoding:error:)'

我不知道该怎么做,希望你们中的一些人知道,提前谢谢

最佳答案

//----- 2 ------
func readFile(fileName: String, fileType: String) -> String{
    var fileRoot = NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)
    var contents = NSString.stringWithContentsOfFile(fileRoot!, encoding: NSUTF8StringEncoding, error: nil)
    return contents
}

// example: read file.txt
var contents = readFile("ISO", "csv")
println(contents)


//----- 3 -----

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)

这两个都使用了错误的初始化器语法,如错误状态所示。他们也做同样的事情。

修复:

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)

关于xcode - Swift - 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301034/

相关文章:

swift - Collection View 中的 ImageView 必须居中且宽高比适合快速

xcode - 为什么当我修改项目中的任何 swift 文件时,所有 objective-c 源文件都会重新编译?

php - 在 PHP 中读取文件的特定行

c# - GDI+ 中发生一般性错误(屏幕截图 SaveAsFile、ExternalException)

ios - 在 XCode 8 中切换到新 iPhone 后的 Provisioning Profile 问题

快速更改现有按钮/标签的尺寸和位置

在 C 中复制文件

swift - 在事件监视器 OS X 中防止错误 "funk"声音

core-data - Swift - 在应用程序组中共享核心数据模型(带扩展)

ios - Swift - 为 SOAP Web 服务创建请求和解析响应