[英]Swift iOS -How to sort array of individual objects into separated arrays based on similar property
I have an array
of Super Hero objects. 我有array
的Super Hero对象。 I want to group the superheroes based on the name property
into separated arrays
and then count how many objects are in each individual separated array
我想将基于name property
的超级英雄分组到separated arrays
,然后计算每个单独的separated array
有多少个对象
Object: 宾语:
class SuperHero{
var name: String?
var power: Bool?
}
Array of superheroes (there can be an infinite num of superheroes) 超级英雄数组(可以有无数个超级英雄)
var superHeroes = [SuperHero]()
let superHero1 = SuperHero()
superHero1.name = "SuperMan"
superHero1.power = true
superHeroes.append(superHero1)
let superHero2 = SuperHero()
superHero2.name = "BatMan"
superHero2.power = true
superHeroes.append(superHero2)
let superHero3 = SuperHero()
superHero3.name = "BatMan"
superHero3.power = true
superHeroes.append(superHero3)
let superHero4 = SuperHero()
superHero4.name = "SuperMan"
superHero4.power = true
superHeroes.append(superHero4)
//etc...
Use name property to sort: 使用名称属性进行排序:
let sortedHeros = superHeroes.sort{$0.name < $1.name}
for hero in sortedHeros{
print(hero.name)
/*
prints
BatMan
BatMan
SuperMan
SuperMan
*/
}
How do I put the sorted array into separate arrays then print the count of each separated array? 如何将排序后的数组放入单独的数组中,然后打印每个单独的数组的计数?
//this is what I want
separatedArraysOfSuperHeroes = [[superHero2, superHero3], [superHero1, superHero4]]
//subscriprting isn't ideal because i'll never know the exact number of separated arrays
print(separatedArraysOfSuperHeroes[0].count)
print(separatedArraysOfSuperHeroes[1].count)
As per the comments the reason why I want sub arrays is because I want to use them to populate different tableview sections. 根据评论,我想要子数组的原因是因为我想使用它们来填充不同的tableview部分。 For ie inside my tableview I would now have a 2 sections. 例如,在我的tableview中,我现在有两个部分。 The first section would have a header that says "Batman" with 2 Batman objects inside of it and the second section would have a header that says Superman with 2 Superman objects inside of it. 第一部分的标题为“ Batman”,里面有2个蝙蝠侠对象,第二部分的标题为“超人”,里面有2个超人对象。 The count property would show the number of super hero objects inside each section. count属性将显示每个部分中超级英雄对象的数量。
func getSeparatedArrayBasedOnName(superHeroes: [SuperHero]) -> [[SuperHero]] {
guard let superNames = NSOrderedSet.init(array: superHeroes.map { $0.name ?? "" }).array as? [String] else {
print("Something went wrong with conversion")
return [[SuperHero]]()
}
var filteredArray = [[SuperHero]]()
for superName in superNames {
let innerArray = superHeroes.filter({ return $0.name == superName })
filteredArray.append(innerArray)
}
for array in filteredArray {
for hero in array {
print(hero.name ?? "")
}
}
return filteredArray
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.