错误:对 Swift 3 中成员“下标"的不明确引用 [英] Error: Ambiguous reference to member 'subscript' in Swift 3

查看:29
本文介绍了错误:对 Swift 3 中成员“下标"的不明确引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下载了 Xcode 8 beta 并将我的语法转换为 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):

斯威夫特 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")
}

斯威夫特 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")
}

这是 Swift 3 中的错误,还是我遗漏了什么?

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.

提前致谢!

推荐答案

我认为这样的事情应该可行:

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)")
}

因为 NSFileSize 只是一个常量字符串,所以我用它的原始值替换了它.看起来没问题 - 但当然最好找到官方的等价物(我现在没能做到,所以不要认为这个解决方案是理所当然的,这只是一种解决方法).

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).

Xcode 8 GM 更新:

使用 FileAttributeKey.size 比使用硬编码常量更好(感谢 @rudy提醒).这是一个更新的示例:

Using FileAttributeKey.size is better than using the hardcoded constant (thanks @rudy for the reminder). Here's an updated example:

do {
    let attributes = try FileManager.default.attributesOfItem(atPath: file.path)
    if let size = attributes[FileAttributeKey.size] as? NSNumber {
        let fileSize = size.int64Value
        print(fileSize)
    }
} catch {
    print(error.localizedDescription)
}

这篇关于错误:对 Swift 3 中成员“下标"的不明确引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆