Swift中如何在嵌套数组内搜索并追加值?
Swift 实现追加新值到教师评论字段开头的函数
首先,原给定的教师信息数组是不可变的(用let声明),要修改内容需先将其改为可变数组(var):
var 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"] ]
需求说明
实现名为addnewValuesForTeachers的函数,接收teacherName(匹配的教师姓名)和newValues(待追加的内容)两个参数。找到对应教师后,将新值追加到其comments字段的开头(示例:传入"Ian"和"technician"后,对应元素变为["Ian", "technician, scientist,male, no_available"])。
完整实现逻辑
核心步骤
- 跳过表头(数组第一个元素),遍历教师数据
- 匹配目标教师姓名
- 基于题目要求的
insert方法,将新值前缀插入到评论字符串开头 - 更新数组中对应位置的教师数据
完整代码实现
func addnewValuesForTeachers(teacherName: String, newValues: String) { // 从索引1开始遍历,跳过表头 for index in 1..<teachersInfo.count { let currentTeacher = teachersInfo[index] guard currentTeacher.first == teacherName else { continue } // 处理评论内容:用insert方法插入新值前缀 var commentCharacters = Array(currentTeacher[1]) // 构造要插入的前缀(新值+分隔逗号) let prefix = Array("\(newValues), ") // 将前缀插入到字符串的起始位置 commentCharacters.insert(contentsOf: prefix, at: 0) let updatedComment = String(commentCharacters) // 更新数组中的教师数据 teachersInfo[index] = [teacherName, updatedComment] // 若姓名唯一,找到后提前退出循环提升效率 break } }
补充说明
- 如果允许存在同名教师,可删除
break语句实现批量更新 - 若原评论为空,会自动将新值作为唯一评论内容
- 若不需要严格使用
insert方法,也可以直接用字符串拼接"\(newValues), \(currentTeacher[1])",效果一致
测试示例
调用函数验证结果:
// 测试调用 addnewValuesForTeachers(teacherName: "Ian", newValues: "technician") // 输出Ian的最新数据 print(teachersInfo[1]) // 输出结果:["Ian", "technician, scientist,male, no_available"]
内容的提问来源于stack exchange,提问作者ZeroCooL
相关产品推荐
相关产品推荐

