ghostpotato ghostpotato - 5 months ago 826
iOS Question

Error: Ambiguous reference to member 'subscript' in Swift 3

I downloaded the Xcode 8 beta and converted my syntax to Swift 3. When I did, I got the eponymous error with this code (this didn't happen before):

Swift 3:

do {
let fileAttributes = try FileManager.default().attributesOfItem(atPath: fileURL.path!) // Error here
let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber
fileSize = fileSizeNumber.longLongValue
} catch _ as NSError {
print("Filesize reading failed")
}


Swift 2:

do {
let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(fileURL.path!)
let fileSizeNumber = fileAttributes[NSFileSize] as! NSNumber
fileSize = fileSizeNumber.longLongValue
} catch _ as NSError {
print("Filesize reading failed")
}


Is this a bug in Swift 3, or am I missing something?

I know there are many questions about the same error, but those don't fix my problem. I'm happy to edit for clarification.

Thanks in advance!

Answer

I think something like this should work:

do {
    let fileAttributes = try FileManager.default().attributesOfItem(atPath: file.path!)
    if let fileSizeNumber = fileAttributes["NSFileSize"] as? NSNumber {
        let fileSize = fileSizeNumber.int64Value

    }
} catch let error as NSError {
    print("Filesize reading failed: \(error.debugDescription)")
}

Since NSFileSize was just a constant string I've replaced it by its raw value. It seems ok - but it would be better to find the official equivalent, of course (which I didn't manage to for now, so don't take this solution for granted, it's just a workaround).