Swift 3:如何为(;;)循环写这个

时间:2016-03-23 12:21:52

标签: for-loop swift3

看起来Apple并不喜欢C循环,但是它并没有提供好的方法(或者我找不到它)。我有这样的循环从一些视图到UI层次结构中的根:

for var parentView = view; parentView != nil; parentView = parentView.parent {
    ...
}

如何用Swift 3方式写这个?

3 个答案:

答案 0 :(得分:2)

这将是Swift 3中的一种方式:

IsDate(txtDate.Text)

如果要将循环进度内容分组到var parentView: View! = view while parentView != nil { // Do stuff parentView = parentView.parent } 旁边而不是在块结尾处,可以使用while,如下所示:

defer

如果您想限制var parentView: View! = view while parentView != nil { defer { parentView = parentView.parent } // Do stuff } 的范围,可以将所有内容封装在parentView块中:

do

但它非常详细,所以你可以为类似的循环定义一个新的泛型函数,如下所示:

do {
    var parentView: View! = view
    while parentView != nil {
        defer { parentView = parentView.parent }        
        // Do stuff
    }
}

最后一个依赖于func kindaCStyleLoop<T>(first: T, obtainNext: T -> T?, action: T -> ()) { var current: T! = first repeat { action(current) current = obtainNext(current) } while current != nil } kindaCStyleLoop(view, obtainNext: { $0.parent }) { // Do stuff with $0 } GeneratorType来启用for-in-loop语法:

SequenceType

答案 1 :(得分:1)

正确但过于迟到的回答:Swift 3中有内置函数提供解决方案:

public func sequence<T>(first: T, next: (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>
public func sequence<T, State>(state: State, next: (inout State) -> T?) -> UnfoldSequence<T, State>

我们可以这样使用它们:

sequence(first: view, next: {
    // do something with $0...
    return $0.superview
})

答案 2 :(得分:0)

例如

getView