C语言for语句在swift 3中已弃用

时间:2017-02-06 07:22:59

标签: swift loops swift3

如何更改代码,因为在swift 3中不推荐使用C style for statement?我在以下代码行中收到错误:

for var frame = 0; frame <= frameCount; frame += 1

func keyframePathsWithDuration(_ duration: CGFloat, lastUpdatedAngle: CGFloat, newAngle: CGFloat, radius: CGFloat, type: RMIndicatorType) -> [CGPath] {
    let frameCount: Int = Int(ceil(duration * 60))
    var array: [CGPath] = []
    for var frame = 0; frame <= frameCount; frame += 1 {
        let startAngle = degreeToRadian(-90)

        let angleChange = ((newAngle - lastUpdatedAngle) * CGFloat(frame))
        let endAngle = lastUpdatedAngle + (angleChange / CGFloat(frameCount))
        array.append((self.pathWithStartAngle(startAngle, endAngle: endAngle, radius: radius, type: type).cgPath))
    }
    return array
}

2 个答案:

答案 0 :(得分:2)

以下是如何将C风格的循环转换为快速循环。

如果C-style for循环采用以下形式:

for var i = x ; i < y ; i++ {

将其更改为:

for i in x..<y {

如果是这种形式:

for var i = x ; i <= y ; i++ {

将其更改为:

for i in x...y {

所以在你的情况下,它会变成:

for frame in 0...frameCount {

这是转型的更通用版本:

for var i = x ; i <operator> y ; i += z

为:

for i in stride(from: x, to/through: y, by: z)

答案 1 :(得分:1)

尝试使用Swift 3/4的新语法

func keyframePathsWithDuration(_ duration: CGFloat, lastUpdatedAngle: CGFloat, newAngle: CGFloat, radius: CGFloat, type: RMIndicatorType) -> [CGPath] {
            let frameCount: Int = Int(ceil(duration * 60))
            var array: [CGPath] = []
            for frame in 0...frameCount {
                let startAngle = degreeToRadian(-90)

                let angleChange = ((newAngle - lastUpdatedAngle) * CGFloat(index))
                let endAngle = lastUpdatedAngle + (angleChange / CGFloat(frameCount))
                array.append((self.pathWithStartAngle(startAngle, endAngle: endAngle, radius: radius, type: type).cgPath))
            }
            return array
}

有关新循环语法的更多信息,请参阅:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html