Can you continue the loop if phasing failed in Swift?

This is a very common idiom for continuing a cycle if some condition is not met for an element.

Suppose we want to do something in all of the subspecies of a certain type (and for some reason we don’t want things like ducks). Ideally, we would write:

for view in self.subviews as [NSView] { // cast required in beta 6 if (let specificView = view as? SpecificView) == nil { // <- Error here continue } // Do things at a sensible indentation level } 

The above code failed: "the binding of the template variable cannot appear in the expression", as in this question .

However, it seems like such a big picture that there should be a way in Swift to do this. Did I miss something?


EDIT: now that I am thinking about this, this does not seem to conform to the definition rules for if let that only map the variable to an internal block.

With that in mind, I would like to expand the question a bit: how do people use this template in general in Swift?

+5
source share
1 answer

This is a somewhat common picture, but it is not a very good example. I saw him introduce errors into ObjC projects. He thinks too much about the hierarchy of views and at the same time becomes fragile when it changes (for example, when someone introduces an additional view that you did not expect to control the turns, a true story). The best template is to save a property that points to the SpecificView (or views) that you want to track. Downsizing as a whole is something that should be avoided, not optimized.

However, this is not a scary template, and sometimes it is a very useful pattern. So how can you handle this?

 let specifics = self.subviews .filter { $0 is SpecificView } .map { $0 as SpecificView } for view in specifics { ... } 

Such a general template, perhaps we can generalize it?

 extension Array { func filterByClass<T>(c: T.Type) -> [T] { return self.filter { $0 is T }.map { $0 as T } } } for view in self.subviews.filterByClass(SpecificView) { ... } 

However, I think this approach should be avoided when possible, and not overly simplified.

+10
source

Source: https://habr.com/ru/post/1201072/


All Articles