How to discover and display repeated elements within an Array in Swift 4

Asked

Viewed 282 times

1

I’m new to Stackoverflow and also new to Swift programming.

Could someone more experienced let me know how I identify repeated elements within an array without using Extensions?

Just using for and if.

Thanks for the help and hugs to everyone.

1 answer

1

There are two ways to understand this question, whether you want to know the amount that a given element repeats in an array or how many times each element repeats.

Say you have an array of Strings:

 var names = ["George", "Fabio", "Maria", "Fabio", "Eugenia", "Maria", "Maria"]

If you want to know the amount of repetitions that each element has within that array you can go through that array and store inside a dictionary each repetition where the key is the item and the value is the amount that that item repeated as:


//Dicionário para guardar quantas vezes cada nome foi repetido 
var counts: [String: Int] = [:]

//Percorre todos elementos no array
for name in names {
   //Ele adiciona mais 1 ao contador do nome se estiver repetido
   counts[name] = (counts[name] ?? 0) + 1
}
//Imprime o resultado de todas repetições 
print(counts)

The result is

["Maria": 3, "George": 1, "Eugenia": 1, "Fabio": 2]

If you want to know only how many times an element is repeated in the array you only need one for and compare:


var nameToCount = "Maria"
var result = 0

for name in names{
   if name == nameToCount{
      result = result + 1
   }
}
print("O nome:",nameToCount,"Repetiu",result, "x")

Upshot:

O nome: Maria Repetiu 3 x

Browser other questions tagged

You are not signed in. Login or sign up in order to post.