Arrays Swift-根据元素的相等特征对元素进行分组

Arrays Swift-根据元素的相等特征对元素进行分组,arrays,swift,Arrays,Swift,在Swift 4中,我有: let customers = [Customer(name: "John", country: "US", profession: "Engineer"), Customer(name: "Mary", country: "UK", profession: "Nurse"), Customer(name: "Diana", country: "US", profession: "Engineer"), Customer(name: "Paul", country:

在Swift 4中,我有:

let customers = [Customer(name: "John", country: "US", profession: "Engineer"), Customer(name: "Mary", country: "UK", profession: "Nurse"), Customer(name: "Diana", country: "US", profession: "Engineer"), Customer(name: "Paul", country: "US", profession: "Plumber"), Customer(name: "Sam", country: "UK", profession: "Nurse")]
例如,我希望有一个函数可以过滤
客户
中的元素,以便每次其中至少两个元素的名称和职业相等时,它们都被添加到该函数自动创建的数组中:

var customers1 = [Customer(name: "John", country: "US", profession: "Engineer"), Customer(name: "Diana", country: "US", profession: "Engineer")]
var customers2 = [Customer(name: "Mary", country: "UK", profession: "Nurse"), Customer(name: "Sam", country: "UK", profession: "Nurse")]
我搜索没有成功,但我选择了一些可能适合本案例的解决方案:

extension Array where Element: Comparable {
    func containsSameElements(as other: [Element]) -> Bool {
        return self[1] == other[1] && self[2] == other[2]
    }
}

func==(lhs:[[Element]],rhs:[[Element]])->Bool{
返回lhs.elementsEqual(rhs,by:=)
}

elementsEqual()
/
包含()和循环

flatMap()
/
reduce()
/
filter()
的组合


谢谢。

我建议您这样做:

struct Customer {
    let name: String
    let country: String
    let profession: String

    func countryMatches(with otherCustomer: Customer) -> Bool {
        return country == otherCustomer.country
    }

    func professionMatches(with otherCustomer: Customer) -> Bool {
        return profession == otherCustomer.profession
    }

    func countryAndProfessionMatch(with otherCustomer: Customer) -> Bool {
        return countryMatches(with: otherCustomer) && professionMatches(with: otherCustomer)
    }

    static func getAllCustomersWithProfessionsAndCountriesMatching(with customer: Customer, from allCustomers: [Customer]) -> [Customer] {
        return allCustomers.filter { customer.countryAndProfessionMatch(with: $0) }
    }
}

let arrayOfArrays = [["John", "A", "A" ], ["Mary", "A", "B" ], ["Diana", "A", "A" ], ["Paul", "B", "B" ], ["Sam", "A", "B" ]]

//If you're dealing with non-predictable data, you should probably have some Optionality
let allCustomers = arrayOfArrays.map{ Customer(name: $0[0], country: $0[1], profession: $0[2]) }

let allCustomersMatchingJohnProperties = Customer.getAllCustomersWithProfessionsAndCountriesMatching(with: allCustomers[0], from: allCustomers)  
// contains John and Diane

let allCustomersMatchingMaryProperties = Customer.getAllCustomersWithProfessionsAndCountriesMatching(with: allCustomers[1], from: allCustomers)  
// contains Mary and Sam
我相信这正是您想要做的,但采用了更结构化/可维护的方法


getAllCustomers与Professions和Countries匹配几乎肯定是太长了,但为了清楚答案,还是这样。我建议将其重命名以适合您的用例。

根据您的反馈和说明,我会这样做

struct CountryAndProfession: Hashable, CustomStringConvertible {

    let country: String
    let profession: String


    var description: String {
        return "CountryAndProfession{country: \(country), profession: \(profession)}"
    }

    var hashValue: Int {
        return "\(country)__\(profession)".hashValue
    }
    static func ==(left: CountryAndProfession, right: CountryAndProfession) -> Bool {
        return left.country == right.country && left.profession == right.profession
    }
}

// The Customer Type you apparently are dealing with. (May need a custom init depending on your use case
struct Customer: CustomStringConvertible {
    let name: String
    let countryAndProfession: CountryAndProfession

    var description: String {
        return "Customer{name: \(name), countryAndProfession: \(countryAndProfession)}"
    }

    // returns a dictionary with the passed customer's CountryAndProfession as the key, and the matching
    static func makeDictionaryWithCountryAndProfession(from customers: [Customer]) -> [CountryAndProfession : [Customer]] {
        var customersArrayDictionary: [CountryAndProfession : [Customer]] = [:]

        customers.forEach { (customer) in
            if customersArrayDictionary.keys.contains(customer.countryAndProfession) {
                customersArrayDictionary[customer.countryAndProfession]?.append(customer)
            }
            else {
                customersArrayDictionary[customer.countryAndProfession] = [customer]
            }
        }
        return customersArrayDictionary
    }

    static func getArraysBasedOnCountries(from customerArray: [Customer]) -> [[Customer]] {
        return Array(makeDictionaryWithCountryAndProfession(from: customerArray).values)
    }
}

let arrayOfArrays = [["John", "A", "A" ], ["Mary", "A", "B" ], ["Diana", "A", "A" ], ["Paul", "B", "B" ], ["Sam", "A", "B" ]]

//If you're dealing with non-predictable data, you should probably have some Optionality
let allCustomers = arrayOfArrays.map{ Customer(name: $0[0], countryAndProfession: CountryAndProfession(country: $0[1], profession: $0[2])) }

let splitCustomers = Customer.getArraysBasedOnCountries(from: allCustomers)
//contains [[John, Diana], [Mary, Sam], [Paul]]

我仍然不太确定你希望你的最终结果是什么样的(这总是有助于提出问题),但是,如果使用
makeDictionaryWithCountryAndProfession
并结合您要查找或使用的特定
CountryAndProfession
。filter

,您应该能够得到您想要的结果。该数据结构似乎是一个非常糟糕的选择。如果您所有的数组都有3个元素与第一个元素一起使用作为索引,另外两个是字符串,最好使用元组数组。但无论如何,为什么要将索引存储在数组本身中呢?请解释使用此数据结构您试图实现的目标,然后希望有人能够建议使用更好的数据结构。
[0]
下标不是索引,您可以用字符串替换其中的数字,但它始终与
[2]
[3]
不同。我会编辑它。我想在
数组
中为每组重复项(在上述条件下)创建一个数组。如果要存储特定的非同质值,使用数组无论如何都是个坏主意。它使处理特定数据段的方式变得比它应该的更复杂。原始数据的形式是
阵列射线
。在处理数据之前,我希望进行过滤,但如果有比创建子阵列更好的解决方案来过滤上述条件下的数据(你是说创建自定义类吗?),你能提出一个建议吗?过滤数据结构更复杂,然后先解析为更灵活、更易于使用的格式,然后再过滤。谢谢你的帮助!我真正需要的是在
中识别所有客户
中具有相同国家和相同职业的客户,并自动与他们创建一个属性,但不基于其他客户。例如,我将拥有所有美国客户和工程师的1号房产,以及所有英国客户和护士的2号房产。如果
allCustomers
中至少有两个客户具有相同的国家和行业,则创建一个属性非常重要。如果我不清楚,我很抱歉。我编辑了第一篇文章。@TommyV。根据您的澄清发布了新答案。我想补充一点,如果你有一组已知的国家和职业,他们将是一个很好的枚举候选人。这将使其中的一些更简单。不,国家和职业并不是事先就知道的。这个解决方案正是我想要的:能够根据选定的相等特征对数组元素进行分组。再次感谢PEEJWEEJ!没问题。祝你好运
struct CountryAndProfession: Hashable, CustomStringConvertible {

    let country: String
    let profession: String


    var description: String {
        return "CountryAndProfession{country: \(country), profession: \(profession)}"
    }

    var hashValue: Int {
        return "\(country)__\(profession)".hashValue
    }
    static func ==(left: CountryAndProfession, right: CountryAndProfession) -> Bool {
        return left.country == right.country && left.profession == right.profession
    }
}

// The Customer Type you apparently are dealing with. (May need a custom init depending on your use case
struct Customer: CustomStringConvertible {
    let name: String
    let countryAndProfession: CountryAndProfession

    var description: String {
        return "Customer{name: \(name), countryAndProfession: \(countryAndProfession)}"
    }

    // returns a dictionary with the passed customer's CountryAndProfession as the key, and the matching
    static func makeDictionaryWithCountryAndProfession(from customers: [Customer]) -> [CountryAndProfession : [Customer]] {
        var customersArrayDictionary: [CountryAndProfession : [Customer]] = [:]

        customers.forEach { (customer) in
            if customersArrayDictionary.keys.contains(customer.countryAndProfession) {
                customersArrayDictionary[customer.countryAndProfession]?.append(customer)
            }
            else {
                customersArrayDictionary[customer.countryAndProfession] = [customer]
            }
        }
        return customersArrayDictionary
    }

    static func getArraysBasedOnCountries(from customerArray: [Customer]) -> [[Customer]] {
        return Array(makeDictionaryWithCountryAndProfession(from: customerArray).values)
    }
}

let arrayOfArrays = [["John", "A", "A" ], ["Mary", "A", "B" ], ["Diana", "A", "A" ], ["Paul", "B", "B" ], ["Sam", "A", "B" ]]

//If you're dealing with non-predictable data, you should probably have some Optionality
let allCustomers = arrayOfArrays.map{ Customer(name: $0[0], countryAndProfession: CountryAndProfession(country: $0[1], profession: $0[2])) }

let splitCustomers = Customer.getArraysBasedOnCountries(from: allCustomers)
//contains [[John, Diana], [Mary, Sam], [Paul]]