Home > database >  how to search and append value in array inside array
how to search and append value in array inside array

Time:09-01

i have this input

let teachersInfo: [[String]] = [
      ["names", "comments"],
      ["Ian", "scientist,male, no_available"],
      ["Mark", "teacher,elementary school,female, available_for_new"],
      ["Bryan", "interior designer,male,no_available"],
      ["Tomas", "profesional surfer,master"],
      ["Justine", "no_available, scientist"],
      ["Malek", "teacher, elementary school, available_for_new"],
      ["Adrian", "scientist, profesional surfer, available_for_new"],  
      ["Mike", "elementary schoole,male,no_available"]
    ]

i want to create a function for search and append a value when it founds a match for for example

func addnewValuesForTeachers(teacherName: String, newValues: String){
    if teachersInfo.contains(teacherName){
        //for example if teacherName was 'Ian' and newValues are "technician"
        //should look like
        //["Ian", "**technician** , scientist,male, no_available"]
    }
    
}

i know can insert values like this:

teachersInfo[0].insert(name, at: position)

CodePudding user response:

I would restructure this into real structs with properties, but if you want to stay with this [[String]] you would need to get the index of your array. Then replace that String with the value you want to add plus the original String:

func addnewValuesForTeachers(teacherName: String, newValues: String){
    guard let index = teachersInfo.firstIndex(where: { item in
        item[0] == teacherName
    }) else {
        return
    }
    
    teachersInfo[index][1] = "\(newValues), \(teachersInfo[index][1])"
}

proof

  • Related