Replacement for C-style loop in Swift 2.2 CGFloat

二次信任 提交于 2019-12-24 12:51:54

问题


I have tried this with CGFloat and i am getting the following error: Can not invoke stride with an argument list of type '(CGFloat by: CGFloat)'

for var min:CGFloat = 0.0; min<=45.0; min = min+value {

print("\(min)")
}

to:

for min:CGFloat in 0.stride(CGFloat(55.0), by: min+value) {

   print("\(min)")
}

回答1:


Below is the latest overload for stride. You can use cast the number to CGFloat for the stride.

for min in (0 as CGFloat).stride(to: 55, by: value) {
    print("\(min)")
}

However, stride returns a Striable when the for-loop begin. The by value does not update with the iteration of for-loop. A while-loop would be better for this case,

var min : CGFloat = 0

while (min < 55) {
    print("\(min)")
    min += value
}



回答2:


import Foundation

let fromValue = CGFloat(0.0)
let toValue = CGFloat(10.0)
let distance = CGFloat(3.3)


// stride in interval from 0.0 ..< 10.0, with distance 3.3

let sequence = fromValue.stride(to: toValue, by: distance)
print(sequence.dynamicType)
/*
 StrideTo<CGFloat>
 */

// StrideTo conforms to SequenceType protocol, so we can use for-in
for element in sequence {
    print("\(element)")
}
/*
 0.0
 3.3
 6.3
 9.9
*/


来源:https://stackoverflow.com/questions/36289786/replacement-for-c-style-loop-in-swift-2-2-cgfloat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!