我有這樣的循環:重複一次迭代
let names = ["Sandra", "Pedro", "John", "Shay", "Tyrion"]
var money = 0
for var nameIndex in 0..<names.count {
if money > 30 {
print("This name is to be repeated: \(names[nameIndex])")
money = 0
nameIndex -= 1
continue
}
money += 25
print("Her name is \(names[nameIndex])")
}
我期待這樣的輸出:
Her name is Sandra
Her name is Pedro
This name is to be repeated: John
Her name is John
Her name is Shay
Her name is Tyrion
然而,似乎
nameIndex -= 1
不影響實際變量。它暫時減少它,但只要下一次迭代發生,變量就會恢復正常。
實際的輸出是:
*Her name is Sandra
Her name is Pedro
This name is to be repeated: John
Her name is Shay
Her name is Tyrion*
這是因爲如果nameIndex - = 1並沒有什麼影響。
我該如何做到這一點?換句話說,我如何在下一次迭代中再次迭代一個項目。
PS:我上面發佈的示例是描述我的真實應用程序的簡化方式。這是爲了使這項工作:
for var word in 0..<rawText.count {
let wordText = rawText[word]
let wordLabel = SKLabelNode(fontNamed: "LCDSolid")
wordLabel.text = wordText
if scalingFactor == nil {
scalingFactor = getScalingFactor(labelNode: wordLabel, size: adjustedSize)
}
wordLabel.fontSize *= scalingFactor
let addedWidth = wordLabel.frame.width + self.size.width * CGFloat(0.03)
currentWidth += addedWidth
if currentWidth > desiredWidth {
currentPos = (self.size.width * CGFloat(-0.475), currentPos.y - adjustedSize.height * CGFloat(1.5))
currentWidth = 0
word -= 1
continue
}
wordLabel.position = CGPoint(x: currentPos.x + (wordLabel.frame.width * CGFloat(0.5)), y: currentPos.y)
currentPos.x += addedWidth
print("width is \(wordLabel.frame.width) and current width is \(currentWidth) and actual box width is \(self.size.width)")
self.addChild(wordLabel)
}
}
但我認爲它會更簡單的工作一個簡單的例子。
讓名=「桑德拉」,「佩德羅」,「約翰」,「吉文」,「提利昂」 ] var money = 0 ??? –