Home Loop for variables (Xcode 9 - swift 4)
Reply: 2

Loop for variables (Xcode 9 - swift 4)

Burnside Published in 2017-11-13 14:32:42Z

I have I think a stupid question for you, but I start Xcode just one week ago and I have a problem with a loop condition.

for index in 1...4 {
    AvatarPlayer1.layer.borderWidth = 4
    AvatarPlayer1.layer.cornerRadius = 8
    AvatarPlayer1.layer.borderColor = UIColor.white.cgColor
    AvatarPlayer1.layer.masksToBounds = false
    AvatarPlayer1.clipsToBounds = true //Mask for picture

How can I change the 1 value by for number in the loop. I have try + , + \(index), + index.

matt Reply to 2017-11-13 14:44:35Z

You cannot change a variable name in code. Instead, start with an array of your four AvatarPlayer objects and cycle through the array:

let myArrayOfAvatarPlayers = [AvatarPlayer1, AvatarPlayer2, AvatarPlayer3, AvatarPlayer4]
for thisPlayer in myArrayOfAvatarPlayers {
    thisPlayer.layer.borderWidth = 4
    thisPlayer.layer.cornerRadius = 8
    thisPlayer.layer.borderColor = UIColor.white.cgColor
    thisPlayer.layer.masksToBounds = false
    thisPlayer.clipsToBounds = true //Mask for picture
Tobonaut Reply to 2017-11-13 14:50:25Z

In addition to matt's answer, you could move the setup up stuff to the object init or setup method.

After that, you could use init(repeating:count:) for the list's init. See: https://developer.apple.com/documentation/swift/array/1641692-init

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328497 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO