我有一些水果篮,它们都有随机数量的苹果,它们有不同的属性。
arrayOfBaskets = [
["basketId": 1, "typeOfPesticidesUsed": 1, "fromCountry":1, "numberOfApples": 5],
["basketId": 2, "typeOfPesticidesUsed": 1, "fromCountry":1, "numberOfApples": 6],
["basketId": 3, "typeOfPesticidesUsed": 2, "fromCountry":1, "numberOfApples": 3],
["basketId": 4, "typeOfPesticidesUsed": 2, "fromCountry":1, "numberOfApples": 7],
["basketId": 5, "typeOfPesticidesUsed": 1, "fromCountry":2, "numberOfApples": 8],
["basketId": 6, "typeOfPesticidesUsed": 1, "fromCountry":2, "numberOfApples": 4],
["basketId": 7, "typeOfPesticidesUsed": 2, "fromCountry":2, "numberOfApples": 9],
["basketId": 8, "typeOfPesticidesUsed": 2, "fromCountry":2, "numberOfApples": 5]
]
在这种情况下,我如何制定一种类型的算法来输出到这样的数组中:
uniquePairingOfBasketProperties = [
["typeOfPesticidesUsed": 1, "fromCountry":1],
["typeOfPesticidesUsed": 2, "fromCountry":1],
["typeOfPesticidesUsed": 1, "fromCountry":2],
["typeOfPesticidesUsed": 2, "fromCountry":2]
]
我的主要观点是,我可以让我的UITableView知道它应该有多少行。在这种情况下,这是4而不是篮子的总数。
答案 0 :(得分:1)
咦?你有一系列词典。您想将这些词典划分为“桶”,其中每个桶都具有农药类型和原产国的独特组合吗?
假设情况如此,那怎么样:
let kNumberOfCountries = 2
uniqueValue = basket["typeOfPesticidesUsed"] * kNumberOfCountries +
basket["fromCountry"]
uniqueValue
将根据农药类型大幅跳跃,然后根据原产国改变1秒。 (想想一个矩形网格,其中国家/地区编号从左侧1开始向右增加,农药编号从顶部的1开始,随着您的下降而增加。左上角的唯一值编号为1 ,计数到右边,然后换行到下一行并继续计数1秒。
然后,您可以根据uniqueVaue
对表格视图进行分组。
如果您想知道有多少独特的配对,请创建一组空的整数。循环通过你的篮子阵列。计算该篮子的uniqueValue,并将其添加到uniqueValues集合(每个值只有一个条目。)完成循环后,集合中的条目数是您拥有的唯一对的数量。如果您使用NSCountedSet
,您甚至可以获得每次配对的篮子数量。 (我不知道Swift是否有本机计数集合。我上次检查时没有。)
看起来Swift没有本机计数集合集(至少现在还没有。)然而,在Github上至少有一个open source Swift counted set(又名一个包)