Rumo
Rumo

Reputation: 33

iterating though two arrays to output values

So I have two arrays a name array and a values array they are a string and double respectively. I want to be able for a user to type in a textfield and to iterate though the name array until there is a match then output the value that has the same number as the name to be outputted

this is the code i have:

    for(var i = 0; i<name.count; i++){
        if name[i] == typeFood{
            yieldOutput == percent[i]

        }
    } 

Upvotes: 1

Views: 29

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

First, use find to locate the location of the value in the name array, then use the returned index to look up the percent:

if let idx = find(name, typeFood) {
    yieldOutput = percent[idx]
}

You can also combine the two actions together with map to declare an output variable using let:

if let foodPercentage = find(name, typeFood).map({ percent[$0] }) {
    // foodPercentage will have a value here
}
else {
    // not-found logic here
}

Upvotes: 3

Related Questions