UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

how to map elements of an array with their occurrence number

Forums > Swift

Hello,

I have an array of objects that has a type attribute of enum Animals. the type can be like this [Cat, Dog, Cat, Cat, Dog, Mouse, Dog]

I would like to display to my view an output of an image for every object along with the type and its number.

My problem is I cannot get the number from the array. The output should look like :

[Cat1, Dog1, Cat2, Cat3, Dog2, Mouse1, Dog3]

Any ideas how can i achieve this?

2      

Since there are duplicates I don't believe there is a built-in function to find it. However you can create your own.

You will need to use .firstIndex(of:) as you loop through the array and each time removing the item from the array. So you will need to use some temporary array within the function, and a number property within the function to use when displaying.

From what I understand, you want to display the image, and each time it appears you display it's position in the array. So remember to add 1 to the index you get because arrays are zero index.

2      

Something like this:

let data = ["Cat", "Dog", "Cat", "Cat", "Dog", "Mouse", "Dog"]
var countDict: [String:Int] = [:]
let newData: [String] = data.map {
    let count = countDict[$0, default: 1]
    countDict[$0] = count + 1
    return "\($0)\(count)"
}

Output:

["Cat1", "Dog1", "Cat2", "Cat3", "Dog2", "Mouse1", "Dog3"]

Obviously, I used strings as the element type of the initial array but you can adjust this to whatever type you are actually working with.

2      

Where do the numbers come from? Are they associated values of the enum cases? Are they simply generated sequentially from the order in the array?

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.