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

Hi,

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
                Text(String(letters[num]))
                    .padding(5)
                    .font(.title)
                    .background(enabled ? .blue : .red)
                    .offset(dragAmount)
                    .animation(.linear.delay(Double(num) / 20), value: dragAmount)
            }
        }

3      

@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
     Text(String(letters[num]))
}

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!

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.