2016-04-07 22 views
2

我在我的應用程序有這樣一個循環風格:斯威夫特3:更換for循環使用float增量

for var hue = minHue; hue <= maxHue; hue += hueIncrement 
{ 
    let randomizedHue = UIColor.clipHue(
     Random.uniform(ClosedInterval(hue - dispersion, hue + dispersion)) 
    ) 
    colors.append(colorWithHue(randomizedHue)) 
} 

hueIncrement浮動,所以我不能使用範圍運營商這樣的:..<

什麼是在Swift 3中實現這樣的循環的最好和最簡潔的方法?

+2

像'在(minHue)色調。步幅(通過:maxHue,通過:hueIncrement){...}' –

+1

你是對的!你能發表一個答案,所以我可以關閉這個問題嗎? – kelin

+1

無論如何,由於精度的損失,您不應該使用帶有Float的循環。 – gnasher729

回答

16

可以用步幅功能stride(through:, by:)這個..像

for hue in (minHue).stride(through: maxHue, by: hueIncrement){ 
    // ... 
} 

Swift3.0,您可以使用stride(from:to:by:)stride(from:through:by:)語法

for hue in stride(from: minHue, through: maxHue, by: hueIncrement){ 
    //.... 
}