TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.