Swift 2.2 decrementing specific for loop in Swift 3

送分小仙女□ 提交于 2019-12-02 07:50:54

Your code isn't counting the number of 3-letter words in the array. It is counting the number of 3-letter words at the end of the array. It will return 0 for your sample input array.

When a C-style for loop is very complex, the final fallback solution is to translate it to a while loop. Any C-style for loop can be mechanically converted into an equivalent while loop, which means you can do it even if you don't fully understand what it is doing.

This for loop:

for initialization; condition; increment {
    // body
}

is equivalent to:

initialization
while condition {
    // body
    increment
}

So, your code is equivalent to:

let array = ["hello", "world", nil, "foo", nil, "bar", "Peter Griffin"]
var threeLetterWords = 0

var i = array.count - 1
while i >= 0 && array[i]?.characters.count == 3 {
    i -= 1
    threeLetterWords += 1
}
print("Found words: \(threeLetterWords)") // says `Found words: 0`

Here is how to use a for loop and guard to do the equivalent of your code:

let array = ["hello", "world", nil, "foo", nil, "bar", "Peter Griffin"]
var num3LetterWords = 0

for word in array.reversed() {
    guard word?.characters.count == 3 else { break }
    num3LetterWords += 1
}

print(num3LetterWords)
//for var i = array.count-1; i >= 0 && array[i].characters.count == 3; --i, ++threeLetterWords { }

for i in stride(from: (array.count-1), through: 0, by: -1) {
    threeLetterWords += 1

    if (array[i]?.characters.count == 3) {
        break
    }
}

You can use your array indices reversed and add a where clause for the characters count:

let array = ["hello", "world", nil, "foo", nil, "bar", "Peter Griffin"]
var threeLetterWords = 0

for index in array.indices.reversed() where array[index]?.characters.count == 3 {
    threeLetterWords += 1
}

print("Found words: \(threeLetterWords)") // should say `Found words: 2`

Everybody here is very unnecessarily complicating this.

let words = ["hello", "world", nil, "foo", nil, "bar", "Peter Griffin"]

var num3LetterWords = 0

for word in words.reversed() {
    if (word?.characters.count == 3) { num3LetterWords += 1 }
}

print(num3LetterWords)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!