2017-03-08 36 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