UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Project 7 Animating gestures, basic question and etc

Forums > 100 Days of SwiftUI


I just got a member here~!

I have a basic question, class at Animating gestures,

I would like to know why I should use array of num at "(letters[num])"

and why do I have to use at ForEach, "letters.count"

I also would like to know how to upload images

thank you!

let letters = Array("Hello swift")
    @State var enabled = false
    @State var dragAmount = CGSize.zero

HStack {
            ForEach(0..<letters.count, id:\.self) { num in
                    .background(enabled ? .blue : .red)
                    .animation(.linear.delay(Double(num) / 20), value: dragAmount)


@rocknowyo asks:

and why do I have to use at ForEach, "letters.count"

// WHY do you have to use letters.count ??

ForEach(0..<letters.count, id:\.self) { num in

Try this! Change the letter.count to 5. Then run your code!

If you change it to 5 what does XCode show onscreen? You'll see that you are only getting the first four letters of the string "Hello Swift". Why?

The string "Hello Swift" has eleven characters, including ONE space.

The ForEach(xxxxxxx) statement is building a Text() view for each letter that you provide.

If you only ask for (0..<5) you only get these letters...

0 = H
1 = e
2 = l
3 = l
4 = o

But if you want to render the entire string -- Hello Swift -- you need to know how many letters are in this string.

An easy way to figure this out is to tell SwiftUI that you would like ONE text view for all the letters ( letters.count ) in the string.

Keep coding!


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.