Max Goddard
Max Goddard

Reputation: 25

How to append all elements of an array to a label through a for loop in Swift

I have an array weekOneExerciseArray that has 4 strings inside of it. I have a label that I want to assign each of these strings to, each on a new line. At the moment I've just written the individual array elements before attempting to write a more optimised version. However I get

Cannot subscript a value of type '[String]' with an index of type

on the exerciseString = "\(exerciseString)\n (weekOneExerciseArray[exerciseCount])"; } line.

I've tried so many variants to get this working but to no luck. I would be very thankful for any help!

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;

Upvotes: 1

Views: 1625

Answers (1)

Ahmad F
Ahmad F

Reputation: 31645

The reason for getting the error is in the for-in you are trying to access an element of an array by using a string as an index:

for exerciseCount in weekOneExerciseArray
{
    exerciseString = "\(exerciseString)\n\(weekOneExerciseArray[exerciseCount])";
}

At this point, exerciseCount is a string but not an integer, so what you should do instead is:

for i in 0..<weekOneExerciseArray.count {
    exerciseString = "\(exerciseString)\n\(weekOneExerciseArray[i])"
}

and you would be good to go.


A Better Solution

However, I would highly recommend to follow the following approach instead:

You could group up weekOneExerciseArray by joining its elements using joined method for generating the desired concatenation:

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

Upvotes: 4

Related Questions