Swift 4数据读取选项[重复]

问题描述 投票:1回答:3

这个问题在这里已有答案:

这个Objective C代码行到Swift 4的正确翻译是什么?

NSData *mappedData =
  [NSData dataWithContentsOfURL:fileURL
                        options:NSDataReadingMappedAlways + NSDataReadingUncached
                          error:&error];

我试过这个,但它没有编译:

 Data(contentsOf: fileUrl, options: Data.ReadingOptions.dataReadingMapped | Data.ReadingOptions.uncached)
ios objective-c swift4 nsdata
3个回答
2
投票

你可以试试

do {

     // note it runs in current thread

    let data = try Data(contentsOf:fileURL, options: [.alwaysMapped , .uncached ] )

    print(data)

}
catch {

    print(error)
}

2
投票

您的Swift代码有两个问题。

首先,options需要作为数组的元素传入(不使用你所使用的按位OR运算符 - 该方法被弃用了几个Swift版本):

[.dataReadingMapped, .uncached]

其次,这个初始化程序可以抛出异常,因此您需要考虑到这一点。

有两种方法可以做到这一点:在try-catch块中,或通过可选链接。

如果您希望捕获并响应特定错误,请使用try-catch块:

do {
    let data = try? Data(contentsOf: fileURL, options: [.dataReadingMapped, .uncached])
    // Do something with data
} catch {
    print(error)
}

如果您不关心从特定错误中恢复,可以使用可选链接:

if let data = try? Data(contentsOf: fileURL, options: [.dataReadingMapped, .uncached]) {
    // Do something with data
} else {
    // It failed. Do something else.
}

如果你有兴趣从Objective-C切换到Swift,我会推荐Apple的Swift Programming Language一书:

https://itunes.apple.com/us/book/swift-programming-language/id881256329


-1
投票

试试看,看看

do {
    guard let fileURL = URL(string: "") else {
       return
    }
    let data = try Data(contentsOf: fileURL , options: Data.ReadingOptions(rawValue: Data.ReadingOptions.alwaysMapped.rawValue | Data.ReadingOptions.uncached.rawValue))
     print(data)
} catch {
    //print(error)
}
© www.soinside.com 2019 - 2024. All rights reserved.