【问题标题】:Compare and return a distinct swift array object based on a property根据属性比较并返回一个不同的 swift 数组对象
【发布时间】:2016-09-12 09:01:18
【问题描述】:

我有一个包含一些属性的对象数组。

例如:餐厅{名称、纬度、经度、地址}

我想根据特定属性比较每个对象并返回不同对象的列表。

例如:

Array = [R1, R2, R3, R4, R5]

比方说,R4 和 R5 餐厅距离较近,经纬度相同。

我需要对数组进行比较和过滤

($0.latitude == $1.latitude and $0.longitude == $1.longitude)四舍五入到小数点后三位

这样最终的结果会有以下几项[R1, R2, R3, R4]

【问题讨论】:

    标签: ios arrays swift


    【解决方案1】:

    正如@kandelvijaya 所说,如果您想/必须成对比较元素,我不确定您是否能比二次时间做得更好(这在很多情况下都很好)。

    这是一个通用的 O(n) 替代方案。两件事:

    • 您无需直接比较两个元素,而是提供一个 key 来表示您想要比较的属性。
    • 此密钥需要是可散列的(许多标准类型都是如此)。

    .

    extension Sequence {
        typealias Element = Iterator.Element
    
        func uniqued<Key: Hashable>(by key: (Element) -> (Key)) -> [Element] {
            var seen = Set<Key>()
            return filter {
                seen.update(with: key($0)) == nil
            }
        }
    }
    

    用法:

    let numbers = [1, 1, 1, 2, 2, 3, 1, 2, 3]
    let uniqueByValue = numbers.uniqued { $0 } 
    
    let strings = ["a", "b", "aa", "bb", "ccc", "dddd"]
    let uniqueByLength = strings.uniqued { $0.characters.count }
    

    在你的情况下,这可能是:

    let restaurantes = [R1, R2, R3, R4, R5]
    let uniques = restaurants.uniqued { 
        let roundedLat = ...
        let roundedLong = ...
        return "\(roundedLat), \(roundedLong)"
    }
    

    【讨论】:

    • 谢谢亚瑟。无法尝试您的解决方案。稍后会检查它
    【解决方案2】:
    class B {
        var a: String?
        var b: Int?
    }
    
    var arr:[B] = []
    
    arr.filter{ index in
        var repeatedCount = 0
        arr.forEach{
            repeatedCount += $0.a == index.a ? 1 : 0
        }
        return repeatedCount == 1
    }
    

    上述解决方案可行,但复杂度为 o(arr.count^2),这对于大型项目集不利。

    您可以概括该算法并使其高效。或者在数组distinct上做一个扩展函数

    在您的情况下,代码将是这样的:

    arr.filter{ index in
        var repeatedCount = 0
        arr.forEach{
            if $0.latitude == index.latitude && $0.longitude == index.longitude {
                repeatedCount += 1
            }
        }
        return repeatedCount == 1
    }
    

    【讨论】:

    • 谢谢@kandelvijaya。小更新——我们需要repeatCount += 1 而不是repeatCount += 1 对吧?
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2021-09-10
    • 2020-08-17
    • 2021-11-04
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多