iosnsfilemanagerswift3.2

Swift3 - Binary operator '==' cannot be applied to operands of type 'AnyObject?' and 'FileAttributeType'


I am trying to check FileAttributeType. Here is my logic to compare:-

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

Error-> Binary operator '==' cannot be applied to operands of type 'AnyObject?' and 'FileAttributeType'


Solution

  • The (big) mistake is that you cast a very specific type

    static let type: FileAttributeKey

    The corresponding value is an String object

    to a very unspecific type AnyObject. AnyObject cannot be compared.


    Cast the type to String and compare with the rawValue of the FileAttributeType

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

    Side note: It's highly recommended to use always URLs rather than string paths and get the file attributes directly from the 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)")
    }