我有一个数组weekOneExerciseArray
,里面有4个字符串。我有一个标签,我想分配每个字符串,每个都在一个新行。目前,在尝试编写更优化的版本之前,我只编写了各个数组元素。但是我得到了
无法下标类型' [String]'索引类型为
在exerciseString = "\(exerciseString)\n (weekOneExerciseArray[exerciseCount])"; }
行。
我已经尝试了很多变种来让这个工作但没有运气。我会非常感谢任何帮助!
let weekOneExerciseArray = ["Reverse Crunch", "Crunch", "Oblique Crunch", "Rope Crunch"];
//Week 1: 4 exercises
exerciseTextLabel.text = "\(weekOneExerciseArray[0])\n\(weekOneExerciseArray[1])\n\(weekOneExerciseArray[2])\n\(weekOneExerciseArray[3])";
var exerciseString = "";
for exerciseCount in weekOneExerciseArray
{
exerciseString = "\(exerciseString)\n\(weekOneExerciseArray[exerciseCount])";
}
exerciseTextLabel.text = exerciseString;
答案 0 :(得分:3)
在您尝试使用字符串作为索引访问数组元素的for-in
中获取错误的原因是:
for exerciseCount in weekOneExerciseArray
{
exerciseString = "\(exerciseString)\n\(weekOneExerciseArray[exerciseCount])";
}
此时,exerciseCount
是一个字符串,但不是一个整数,所以你应该做的是:
for i in 0..<weekOneExerciseArray.count {
exerciseString = "\(exerciseString)\n\(weekOneExerciseArray[i])"
}
你会很高兴。
然而,我强烈建议您采用以下方法:
您可以使用joined
方法通过加入其元素来对weekOneExerciseArray
进行分组,以生成所需的连接:
let weekOneExerciseArray = ["Reverse Crunch", "Crunch", "Oblique Crunch", "Rope Crunch"]
let concatenatedString = weekOneExerciseArray.joined(separator: "\n")
print(concatenatedString)
/*
Reverse Crunch
Crunch
Oblique Crunch
Rope Crunch
*/
exerciseTextLabel.text = concatenatedString