Array Pose in Swift

Asked

Viewed 330 times

1

I would like to know how to find the position of an Array in SWIFT

Does anyone know?

var nomes = ["Douglas", "Marilia", "Roberto", "Carol", "Lucas", "Iasmim", "João", "Zeca"]
nomes.append("Franklyn")
print(nomes)
for constante in nomes{
  print("Constante \(constante)")
}

3 answers

2

You can use

if let i = nomes.index(of: "Marilia") {
//Faça o que quiser aqui
}

1

You can do it this way...

let arr:Array = ["Banana","Maça","Laranja"]
find(arr, "Laranja")! // 2

1

Andreza’s answer is correct, but if you need to know the position of an element within a loop you need to use the method enumerated in your array.

var nomes = ["Douglas", "Marilia", "Roberto", "Carol", "Lucas", "Iasmim", "João", "Zeca"]
nomes.append("Franklyn")
print(nomes)
for (index, constante) in nomes.enumerated() {
    print("Constante \(constante) at posição \(index)")
}

Douglas constant at position 0

Marilia constant at position 1

Roberto constant at position 2

Carol constant at position 3

Constant Luke at position 4

Constant Iasmim at position 5

Constant John at position 6

Zeca constant at position 7

Franklyn constant at position 8

Browser other questions tagged

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