0

我的任务是将 iOS 应用程序重构为 Swift 3。但是,有一个forC 风格的循环,它不仅仅是向后循环数组(必须向后循环)。

这是一个示例代码。原理是一样的。

let array = ["hello", "world", nil, "foo", nil, "bar", "Peter Griffin"]
var threeLetterWords = 0
for var i = array.count-1; i >= 0 && array[i].characters.count == 3; --i, ++threeLetterWords { }
print("Found words: \(threeLetterWords)") // should say `Found words: 2`

我试过了,stride(from:through:by:)但我不能增加threeLetterWords,因为在循环中增加它似乎很重要。有任何想法吗?

4

4 回答 4

2
//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
    }
}
于 2017-03-08T02:27:50.723 回答
1

您的代码没有计算数组中 3 个字母单词的数量。它正在计算数组末尾的 3 个字母单词的数量。它将返回0您的示例输入数组。

当 C 风格的 for循环非常复杂时,最终的后备解决方案是将其转换为while循环。任何 C 风格的 for循环都可以机械地转换为等效的while循环,这意味着即使您不完全理解它在做什么,也可以这样做。

这个for循环:

for initialization; condition; increment {
    // body
}

相当于:

initialization
while condition {
    // body
    increment
}

因此,您的代码相当于:

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`

以下是如何使用for循环和守卫来执行与您的代码等效的操作:

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)
于 2017-03-08T02:47:47.850 回答
1

您可以使用反转的数组索引并为字符数添加 where 子句:

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`
于 2017-03-08T02:28:32.160 回答
0

这里的每个人都非常不必要地复杂化了这一点。

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)
于 2017-03-08T05:26:07.590 回答