ios Swift中基于数组长度的for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26694742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:28:07  来源:igfitidea点击:

For loop based on array length in Swift

iosfor-loopswift

提问by user3746428

I have been trying to take the length of an array and use that length to set the amount of times that my loop should execute. This is my code:

我一直在尝试获取数组的长度并使用该长度来设置我的循环应该执行的次数。这是我的代码:

  if notes.count != names.count {
        notes.removeAllObjects()
        var nameArrayLength = names.count
        for index in nameArrayLength {
            notes.insertObject("", atIndex: (index-1))
        }
    }

At the moment I just get the error:

目前我只是收到错误:

Int does not have a member named 'Generator'

Seems like a fairly simple issue, but I haven't yet figured out a solution. Any ideas?

看起来是一个相当简单的问题,但我还没有想出解决办法。有任何想法吗?

回答by vacawama

You need to specify the range. If you want to include nameArrayLength:

您需要指定范围。如果你想包括nameArrayLength

for index in 1...nameArrayLength {
}

If you want to stop 1 before nameArrayLength:

如果您想在 1 之前停止nameArrayLength

for index in 1..<nameArrayLength {
}

回答by Ketan Patel

for i in 0..< names.count {
    //YOUR LOGIC....
}

for name in 0..< names.count {
    //YOUR LOGIC....
    print(name)
}

回答by meaning-matters

In Swift 3 and Swift 4 you can do:

在 Swift 3 和 Swift 4 中,您可以执行以下操作:

for (index, name) in names.enumerated()
{
     ...
}

回答by Paul.s

You can loop over the Array's indices

您可以遍历数组的 indices

for index in names.indices {
    ...
}

If you are just wanting to fill an array with empty strings you could do

如果您只想用空字符串填充数组,您可以这样做

notes = Array(repeating: "", count: names.count)