swift - 等效于循环复杂条件

标签 swift

我的 iOS 项目中当前的代码如下所示:

for var i = 0; CGFloat(i) * gridSpacing.width * scale < bounds.width; ++i

我现在收到警告,称这种风格的 for 循环将被弃用。我在 Stack Overflow 和其他地方看到的所有地方都建议使用 stride 来执行复杂的 for 循环。但是,步幅在这里对我没有帮助,因为结束条件不是与另一个整数的简单比较。

如何使用 for-in 循环快速执行此操作?

注意,我可以循环 CGFloat,但我想通过重复添加 float 来避免增量错误。

我也可以使用 while 循环,但我在同一个函数中有几个这样的循环,并且 for 为 i 创建了一个很好的新作用域。 Swift 似乎不喜欢任意的新作用域。

编辑:根据@Sulthan的回答,我创建了一个SequenceType来执行此操作。 IMO,如果要删除 for 循环,类似这样的事情应该很快发生:

struct forgenerator : GeneratorType
{
    typealias Element = Int
    typealias Condition = (Element) -> Bool
    var idx : Element
    var condition : Condition
    var increment: Element

    mutating func next() -> Element? {
        if condition(idx)
        {
            let result = idx
            idx += increment
            return result
        }

        return nil
    }
}

struct forsequence : SequenceType
{
    typealias Generator = forgenerator
    var startPoint : Generator.Element
    var condition : Generator.Condition
    var increment : Generator.Element

    func generate() -> Generator {
        return forgenerator(idx: startPoint, condition: condition, increment: increment)
    }
}


func forgen(start: Int, condition: (Int) -> Bool, increment: Int) -> forsequence
{
    return forsequence(startPoint: start, condition: condition, increment: increment)
}

func forgen(start: Int, condition: (Int) -> Bool) -> forsequence
{
    return forgen(start, condition: condition, increment: 1)
}

用法:

for i in forgen(0, condition: { CGFloat($0) * self.gridSpacing.width * self.scale < self.bounds.width})

注意,必须在任何地方都使用 self,因为所有这些变量都是类的成员。

最佳答案

总是有递归!避免 while 循环,同时仍然允许您处理不断变化的约束。而且它很实用! ;-)

func recursion(currentIndex: Int) {
    guard CGFloat(currentIndex) * gridSpacing.width * scale < bounds.width else {
        return
    }
    // do what you need to
    recursion(currentIndex + 1)
}

关于swift - 等效于循环复杂条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923799/

相关文章:

macos - 使用 init(rect :inTexture:)?) 时我的 Sprite 发生了什么

swift - 如何在 uilabel 中添加一些文本(以度为单位)?

ios - Swift 在 VC 之间传递数据

ios - UITableView 中的 Swift 异步调用

iOS RxSwift 如何检查 Result == .success?

core-data - 'AnyObject' 没有名为 'contactName' 的成员阻止我的循环

ios - 一段时间后推送 View Controller

swift - 如何使用 swift 处理 JSON 中丢失的对象?

iOS 将电话号码转换为国际格式

ios - 什么时候需要切换 rootViewController