1

What is the correct translation of this Objective C code line to Swift 4?

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

I tried this but it doesn't compile:

 Data(contentsOf: fileUrl, options: Data.ReadingOptions.dataReadingMapped | Data.ReadingOptions.uncached)
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

3 Answers3

4

You can try

do {

     // note it runs in current thread

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

    print(data)

}
catch {

    print(error)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
2

There are two problems with your Swift code.

First, the options need to be passed in as elements of an array, (not using the bitwise OR operator as you have - that method was deprecated several Swift versions back):

[.dataReadingMapped, .uncached]

Second, this initializer can throw an exception, so you need to account for that.

There are two ways to do that: inside a try-catch block, or via optional chaining.

If you want the ability to catch and respond to a specific error then use a try-catch block:

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

If you don't care about recovering from specific errors, you can use optional chaining:

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

I'd recommend Apple's Swift Programming Language book, if you're interested in switching from Objective-C to Swift:

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

Pete Morris
  • 1,472
  • 8
  • 13
-1

Try this and see

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)
}
Krunal
  • 77,632
  • 48
  • 245
  • 261