Array search function not working in Swift

后端 未结 5 1335
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:07

    The possible program flow paths leading to the initialization of age before its return are not exhaustive. In case dataArray is empty, the body of the for ... in loop will never be entered, and age will never initialized. The simplest approach to resolve this issue in your particular example would be simply initialize age to 0 upon it's declaration.

    Regarding the "unexpected" 0 return even in case dataArray contains an element with a name property valued "Steven": for each pass in the for ... in loop that does not contain an element with a name property valued "Steven", you will reset the value of age to 0. This means that only if the "Steven" valued element is the last of the dataArray will the non-0 age value persist. I don't really see any reason to ever set age to 0 again beyond initialization, so you could resolve this by e.g. performing an early exit (break) from the for loop in case of a match. Alternatively, depending on what you want to achieve, simply return items.last_updated from the method upon first match (just note that early return statements could affect performance).

提交回复
热议问题