Array search function not working in Swift

后端 未结 5 1338
Happy的楠姐
Happy的楠姐 2021-01-26 06:20

I confess feeling little stupid, but after hours of trying I have to ask:

class AGE {

     static func getAge() -> Int {

        var age: Int

        for i         


        
5条回答
  •  粉色の甜心
    2021-01-26 07:02

    I'm not Swift developer but I doubt these logics are correct. Assuming you initialise age to 0 as suggested in other answers, after you find the element that matches "Steven" into the array, you should exit. Otherwise the next iteration could set age to zero again.

    Remember, by default for statement iterates through all elements. If you want to iterate till a condition is met, then a while may be more suitable.

    I've read a tutorial and tested this code on line using swift sand box. Sharing my code on this link.

    class AGE {
        static func getAge() -> Int {
            var age = 0
            var found = false
            var current = 0
            var allElementsChecked = (dataArray.count == 0) //is false unless array is empty
            while !found && !allElementsChecked {
                found = (dataArray[current].name == "Steven")
                allElementsChecked = (current == dataArray.count-1)
                current += 1
            }
            if found
            {
                age = dataArray[current-1].age //minus 1 to undo last increment within loop 
            }
            return age
        }
    }
    

    When comes out from the loop that may be because either "Steven" was found or all elements were checked and not found.

提交回复
热议问题