Array search function not working in Swift

后端 未结 5 1337
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:16

    I tested Vadian's answer and it seems to be the correct one as per your requirements.

    Nonetheless, here are other suggestions:

    First, create another instance of your array based on your Person Struct:

    var filteredPerson = [Person]()
    

    If you want to search your dataArray for the age based on the first name:

    func getAge(of name: String){
         filteredPerson = dataArray.filter { $0.name == name }
         print (filteredPerson[0].age) }
    

    To get the age value of "Steven":

    getAge(of: "Steven")
    

    You'll get the Result: 23.

    Note that you can also just get the Int value via return:

    func getAge(of name: String) -> Int {
         filteredPerson = dataArray.filter { $0.name == name }
         return filteredPerson[0].age }
    

    On the other hand, if you have lots of Persons in your list with the same name, and you want to get the age value of a specific Person, just add the lastName parameter:

    func getAge(name: String, lastName: String){
         filteredPerson = dataArray.filter { $0.firstName == name && $0.lastName == lastName }
         print (filteredPerson[0].age) }
    

    And then get the age value via calling:

    getAge(name: "Steven", lastName: "Miller")
    

    Hope this helped someone in some way :)

提交回复
热议问题