4

I have multiple sets of two arrays like that. I am getting them from a 3rd party.

var array1 : [Any?]
var array2 : [Any?]

I know about types of objects in these array (in compile time). As example that first element will be a String and second is an Int.

I currently compare each set of arrays like that (please notice that arrays aren't homogeneous).

array1[0] as? String == array2[0] as? String
array1[1] as? Int == array2[1] as? Int
...

The biggest problem that each set have different types in it. As result, I have let say 10 sets of arrays with 5 elements in each. I had to do 10*5 explicit conversion to specific type and comparation.

I want to be able to write a common method which can compare two arrays like that (without a need to specify all the types)

compareFunc(array1, array2)

I started to go down the road. However, I can't figure out what should I cast the objects too. I tried Equatable. However, swift doesn't like direct usage of it. So, something like that doesn't work

func compare(array1: [Any?], array2: [Any?]) {
    for index in 0..<array1.count {
       if (array1[index] as? Equatable != array2[index] as? Equatable) {
         // Do something
       }
    }
}

Each object in this array will be Equatable. However, I am not sure how to use it in this case.

4

3 回答 3

2

基于(尝试)到已知元素类型的类型转换,构造一个简单的逐元素比较函数

由于您的目标是比较(可选)Any元素的数组,您可以构建一个执行逐个元素比较的函数,方法是使用switch块尝试将数组的元素向下转换为“第 3 方”中的不同已知类型数组”。请注意,您无需指定对应于特定类型的元素位置(因为这可能在不同的数组集之间有所不同),只需指定任何给定元素可能属于的不同类型的详尽集合即可。

这种函数的一个例子如下:

func compareAnyArrays(arr1: [Any?], _ arr2: [Any?]) -> Bool {
    /* element-by-element downcasting (to known types) followed by comparison */
    return arr1.count == arr2.count && !zip(arr1, arr2).contains {
        
        /* note that a 'true' below indicates the arrays differ (i.e., 'false' w.r.t. array equality) */
        if let v1 = $1 {
            
            /* type check for known types */
            switch $0 {
            case .None: return true
            case let v0 as String:
                if let v1 = v1 as? String { return !(v0 == v1) }; return true
            case let v0 as Int:
                if let v1 = v1 as? Int { return !(v0 == v1) }; return true
            /* ...
               expand with the known possible types of your array elements
               ... */
            case _ : return true
                /*  */
            }
        }
        else if let _ = $0 { return true }
        return false
    }
}

或者,或者,通过使用@Roman Sausarnesswitch的帮助函数(稍微修改一下)使块不那么臃肿:s answercompare(...)

func compareAnyArrays(arr1: [Any?], _ arr2: [Any?]) -> Bool {
    
    /* modified helper function from @Roman Sausarnes:s answer */
    func compare<T: Equatable>(obj1: T, _ obj2: Any) -> Bool {
        return obj1 == obj2 as? T
    }
    
    /* element-by-element downcasting (to known types) followed by comparison */
    return arr1.count == arr2.count && !zip(arr1, arr2).contains {
        
        /* note also that a 'true' below indicates the arrays differ
         (=> false w.r.t. equality) */
        if let v1 = $1 {
            
            /* type check for known types */
            switch $0 {
            case .None: return true
            case let v0 as String: return !compare(v0, v1)
            case let v0 as Int: return !compare(v0, v1)
                /* ...
                 expand with the known possible types of your array elements
                 ... */
            case _ : return true
                /*  */
            }
        }
        else if let _ = $0 { return true }
        return false
    }
}

示例用法:

/* Example usage #1 */
let ex1_arr1 : [Any?] = ["foo", nil, 3, "bar"]
let ex1_arr2 : [Any?] = ["foo", nil, 3, "bar"]
compareAnyArrays(ex1_arr1, ex1_arr2) // true

/* Example usage #2 */
let ex2_arr1 : [Any?] = ["foo", nil, 2, "bar"]
let ex2_arr2 : [Any?] = ["foo", 3, 2, "bar"]
compareAnyArrays(ex2_arr1, ex2_arr2) // false
于 2016-05-19T20:02:17.950 回答
1

Aaron Rasmussen的一个紧凑和Swift 5版本的伟大解决方案:

func compare(a1: [Any?], a2: [Any?]) -> Bool {
    guard a1.count == a2.count else { return false }

    func compare<T: Equatable>(obj1: Any, _ obj2: Any, t: T.Type) -> Bool {
        return obj1 as? T == obj2 as? T
    }

    return a1.indices.reduce(true) {

        guard let _a1 = a1[$1], let _a2 = a2[$1] else { return $0 && a1[$1] == nil && a2[$1] == nil }

        switch $1 {
        case 0:  return $0 && compare(obj1: _a1, _a2, t: Int.self)
        case 1:  return $0 && compare(obj1: _a1, _a2, t: String.self)
        case 2:  return $0 && compare(obj1: _a1, _a2, t: <#TypeOfObjectAtIndex2#>.self)
        default: return false
        }
    }
}
于 2019-09-02T09:14:30.377 回答
1

这是一个边际解决方案,但它应该减少您试图避免的一些重复代码:

func compareAnyArray(a1: [Any?], _ a2: [Any?]) -> Bool {

    // A helper function for casting and comparing.
    func compare<T: Equatable>(obj1: Any, _ obj2: Any, t: T.Type) -> Bool {
        return obj1 as? T == obj2 as? T
    }

    guard a1.count == a2.count else { return false }

    return a1.indices.reduce(true) {

        guard let _a1 = a1[$1], let _a2 = a2[$1] else { return $0 && a1[$1] == nil && a2[$1] == nil }

        switch $1 {
        // Add a case statement for each index in the array:
        case 0:
            return $0 && compare(_a1, _a2, t: Int.self)
        case 1:
            return $0 && compare(_a1, _a2, t: String.self)
        default: 
            return false
        }
    }
}

这不是最漂亮的解决方案,但它会减少您必须编写的代码量,并且它应该适用于任何两个[Any?],只要您知道 index 处的类型0是 an Int,并且 index 处的类型1是 a String, ETC...

于 2016-05-19T18:27:31.433 回答