简体   繁体   中英

Swift iOS -How to sort array of individual objects into separated arrays based on similar property

I have an array of Super Hero objects. 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

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. For ie inside my tableview I would now have a 2 sections. 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. The count property would show the number of super hero objects inside each section.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM