How to compare “Any” value types

前端 未结 6 533
我在风中等你
我在风中等你 2020-12-15 05:03

I have several \"Any\" value types that I want to compare.

var any1: Any = 1
var any2: Any = 1

var any3: Any = \"test\"
var any4: Any = \"test\"

print(any1         


        
6条回答
  •  一个人的身影
    2020-12-15 05:25

    You can do it like this by using AnyHashable:

    func equals(_ x : Any, _ y : Any) -> Bool {
        guard x is AnyHashable else { return false }
        guard y is AnyHashable else { return false }
        return (x as! AnyHashable) == (y as! AnyHashable)
    }
    
    print("\(equals(3, 4))")        // false
    print("\(equals(3, equals))")   // false
    print("\(equals(3, 3))")        // true
    

    As not every Equatable has to be Hashable, this might fail under rare circumstances.

    Usually there is no reason for using above hack; but sometimes you will need it, just as sometimes AnyHashable is needed.

提交回复
热议问题