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

时间:2018-09-04 16:21:04

标签: ios nsfilemanager swift3.2

我正在尝试检查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'

1 个答案:

答案 0 :(得分: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)")
}