Array position in Swift

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)")
}
    
asked by anonymous 26.09.2017 / 16:38

3 answers

2

You can use

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

You can do this as follows ...

let arr:Array = ["Banana","Maça","Laranja"]
find(arr, "Laranja")! // 2
    
26.09.2017 / 16:49
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 enumerated method 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)")
}

Constant Douglas at position 0

Constant Marilia at position 1

Constant Robert at position 2

Constant Carol at position 3

Constant Lucas at position 4

Constant Iasmin at position 5

Constant John at position 6

Constant Zeca at position 7

Constant Franklyn at position 8

    
29.09.2017 / 01:05