I'm new to StackOverFlow and also a newbie to Swift programming.
Could anyone more experienced tell me how I can identify repeated elements within an array without using Extensions?
Only using for and if.
Thanks for the help and hugs to all.
I'm new to StackOverFlow and also a newbie to Swift programming.
Could anyone more experienced tell me how I can identify repeated elements within an array without using Extensions?
Only using for and if.
Thanks for the help and hugs to all.
There are two ways to understand this question, whether you want to know how much a given element repeats in an array, or how often each element repeats itself.
Let's 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 inside that array you can go through this array and store within a dictionary each repetition where the key is the item and the value is the amount that this 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 just want to know 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")
Result:
O nome: Maria Repetiu 3 x