Swift3 - 二进制运算符'=='不能应用于'AnyObject'类型的操作数?和'FileAttributeType'

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

我正在尝试检查FileAttributeType。以下是我的比较逻辑: -

let attributes = try fileManager.attributesOfItem(atPath: "/Users/AUSER/Desktop/Downloads")
            print(attributes)

            if (attributes[FileAttributeKey.type] as AnyObject? == FileAttributeType.typeSymbolicLink ){
                print("YESSS \(attributes[FileAttributeKey.type])")
            }

错误 - >二进制运算符'=='不能应用于'AnyObject'类型的操作数?和'FileAttributeType'

ios nsfilemanager swift3.2
1个回答
0
投票

(大)错误是你投了一个非常具体的类型

static let type: FileAttributeKey

对应的值是String对象

一个非常不明确的类型AnyObjectAnyObject无法比较。


将类型转换为String并与FileAttributeType的rawValue进行比较

if attributes[FileAttributeKey.type] as? String == FileAttributeType.typeSymbolicLink.rawValue {

附注:强烈建议使用始终URL而不是字符串路径,并直接从URL获取文件属性

let url = URL(fileURLWithPath: "/Users/AUSER/Desktop/Downloads")
if let resourceValues = try? url.resourceValues(forKeys: [.fileResourceTypeKey]),
    resourceValues.fileResourceType! == .symbolicLink {
    print("YESSS \(resourceValues.fileResourceType!.rawValue)")
}
© www.soinside.com 2019 - 2024. All rights reserved.