Array search function not working in Swift

后端 未结 5 1346
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:21

    As mentioned in the other answers the issue is that the variable will never be set if the array is empty.

    Apart from that your code is inefficient and returns only the expected result if Steven is the last item in the array. Otherwise the variable age gets overwritten with 0.

    Nevertheless in Swift there are more convenient methods to filter an item in an array than a repeat loop, for example first(where:

    class AGE {
    
         static func getAge() -> Int {
            return dataArray.first(where: { $0.name == "Steven" })?.age ?? 0
         }
    }
    

    or it might be preferable to return nil if Steven is not in the array

    class AGE {
    
         static func getAge() -> Int? {
            return dataArray.first(where: { $0.Name == "Steven" })?.age
         }
    }
    

    PS: last_updated in your code is not related to the struct Person at all.

提交回复
热议问题