gpt4 book ai didi

for-loop - swift 3 : how to write this for(;;) loop

转载 作者:行者123 更新时间:2023-12-01 13:45:59 25 4
gpt4 key购买 nike

看起来 Apple 不喜欢 C 循环,但没有提供解决它的好方法(或者我找不到它)。我有这样的循环,从某个 View 转到 UI 层次结构中的根:

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

如何用 Swift 3 的方式写这个?

最佳答案

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

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

如果你想把循环进程的东西放在 while 旁边而不是 block 的末尾,你可以使用 defer,像这样:

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

如果你想限制parentView的范围,你可以把所有的东西封装在一个do block 中:

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
}

最后一个依赖于 GeneratorTypeSequenceType 来启用 for-in-loop 语法:

struct CStyleGenerator<T> : GeneratorType, SequenceType {
let getNext: T -> T?
var current: T!

init(first: T, getNext: T -> T?) {
self.getNext = getNext
self.current = first
}

mutating func next() -> T? {
defer {
if current != nil {
current = getNext(current)
}
}
return current
}
}

for parentView in CStyleGenerator(first: view, getNext: { $0.parent }) {
// Do stuff with parentView
}

关于for-loop - swift 3 : how to write this for(;;) loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com