How to break and return in a loop

I try to access a value in an array of dictionary. The dataArray looks like this:

struct Person {
    let name: String
    let lastName: String
    let age: Int
}

let person1: Person  = Person(name: "Steven", lastName: "miller", age: 23)
let person2: Person = Person(name: "jana", lastName: "drexler", age: 31)
let person3: Person = Person(name: "hanna", lastName: "montana", age: 56)

var dataArray = [Person]()

dataArray.append(person1)
dataArray.append(person2)
dataArray.append(person3)

Now I want to access the age of jana. If I´m doing this:

func getAge() ->Int {

    var age: Int = 0

    for items in dataArray {
        while items.name == "jana" {
            age = items.age

            return age

            break       // This break will never be executed because of return.
        }
        break           // setting the break here, the loop will break after first round
    }
    return age
}

the loop will stop after the first round. (it works only for steven, because he is in the first round of the lopp.) The array is quite long, so i need to stop the loop after the first match. Setting break after return, it will not be executed because of return. Setting return after break, it´s the same. Any suggestions?

For vadian:

class AGE {

    func getAge() -> Int? {

    dataArray.append(person1)
    dataArray.append(person2)
    dataArray.append(person3)

    // Cannot call value of non-function type `Person`
    return dataArray.first(where: { $0.name == "john" }?.age

    }

}

2 answers

  • answered 2017-06-17 19:15 smarx

    How about this? No need for the inner loop (which was never looping anyway).

    func getAge() ->Int {
        for item in dataArray {
            if item.firstName == "jana" {
                return item.age
            }
        }
    
        return 0
    }
    

    As a side note, a dictionary might be a better way to store the data to make lookups more efficient.

  • answered 2017-06-17 19:15 rmaddy

    There is no need for the while loop or the break statements.

    If you want to iterate the loop looking for the age of a specific person, all you need is:

    func getAge() -> Int? {
        for items in dataArray {
            if items.name == "jana" {
                return items.age
            }
        }
        return nil
    }
    

    Note the updated return value to be an optional. A nil return value means the person wasn't found. Don't use 0 as a magic value.

    It's also bad to hardcode the name. Pass it as a parameter. And use better variable names:

    func getAge(of name: String) -> Int? {
        for person in dataArray {
            if person.name == name {
                return person.age
            }
        }
        return nil
    }
    
    if let age = getAge(of: "jana") {
        print("age is \(age)")
    } else {
        print("Name not found")
    }