Home > Mobile >  How to get index of a for loop?
How to get index of a for loop?

Time:08-16

In the following code, I would like to set a max text limit for each String in the array. However, I cannot use ForEach because that is reserved for Views. I would like to be able to grab the index value to accomplish something similar to the following.

    @Published var pollOptions : [String] = [""] {
        didSet {
            ForEach(0..<pollOptions.count, id: \.self) { i in
                if pollOptions[i].count > characterLimit && oldValue[i].count <= characterLimit {
                    pollOptions[i] = oldValue[i]
                }
            }
        }
    }

I need to use something like

for pollOption in pollOptions {
    // code to reset to old value if it exceed characterlimit
}

but I don't quite know how to get the index value to grab oldValue[i]

CodePudding user response:

You can use .enumerated() on collection to get an index per element:

var tmpArray = [
    "foo",
    "bar"
]

tmpArray
    .enumerated()
    .forEach { index, elemen in
        // do something
    }

Hope that helps. On an unrelated not, be careful with property observers on properties with property wrappers especially @Published. You may introduce unwanted side effects.

  • Related