2017-03-08 33 views
0

我有任务将一个iOS应用程序重构为Swift 3.但是,有一个C型的for循环,它不仅仅是向后循环数组(它是强制性的向后)。Swift 2.2递减特定于循环Swift 3

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

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,因为它来增加它的环路显得重要。有任何想法吗?

+0

任何C风格for循环都可以用while循环替换。 – vacawama

+1

您的代码计算阵列末尾的3个字母单词的数量。它会为你的测试数组返回0。 – vacawama

+1

我现在完全理解为什么C样式for循环被删除。 – Alexander

回答

1

你的代码是不计算在阵列中的3个字母的单词的数量。它正在计数数组末尾的3个字母的单词数。它将返回0为您的示例输入数组。

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

循环:

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` 

这里是如何使用环路和后卫做你的代码相同的:这里

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) 
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 
    } 
} 
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` 
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) 
+0

这是执行'print(words.count)'的一种不必要的复杂方法。 – vacawama

+0

@vacawama haha​​ha我忘了复制我的if语句,修复。 – Alexander

+0

你需要解开:'word?.characters.count == 3'。这将计算3个字母的单词,但它不等同于OP的原始代码,该代码实际上会计算数组末尾的3个字母单词的数量。 – vacawama