4 ms·
what sort of cases? Could you use a while loop instead? I feel like (as long as the numerical case optimizes to the same thing) the for-in loop (and occasiona
by rat87 11y ago
what sort of cases?
Could you use a while loop instead?
I feel like (as long as the numerical case optimizes to the same thing) the for-in loop (and occasional use of the while loop) is clearer.
- oscargrouch 11y agoTheres only a case here where iterating over a parent/child relationship, and testing for nullability, its more clear with the c-style for than with a while loop: // old for x: Thing? = thing; x != nil; x = x.parent { ... } // and now var x: Thing? = thing while x != nil { ... x = x.parent } It was the only case i've really missed it.. unless theres a better way to do it that im not aware of.. But the for c-style loop for numbers is really not needed
- rat87 11y agoIdeally that sort of relationship should probably be an iterator, though it's still useful for internal type implementation methods.
- cballard 11y agoI am not sure if there is a name for this type of function, so I called it someFunction: func someFunction<T>(initial: T, next: T -> T?) -> T { var current = initial while true { switch next(current) { case .Some(let value): current = value case .None: return current } } } Now you can express that idea generally, e.g.: extension UIView { var rootView: UIView { return someFunction(self, next: { view in view.superview }) } } I also didn't test it, so it might not work. Of course, it would be more Swifty to create a "Parentable" protocol and write that as an extension of it!