Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Trying to make this common swift pattern more functional.

for object in objects.allObjects {
    guard let _object = object as? SomeTypeOfObject else { continue }
    _object.subObject(subObject, objectStateChanged: changedState)
}
  1. I'd love to use something like "any" (instead of map) to get rid of the for loop - like in Kotlin - but that dose not seem to be possible in Swift.

  2. Trying to figure out a way to include the guard in the functional representation of this block.

Feels like I'm missing something. Am I?

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

A common functional pattern is to compactMap and then call the method with side-effect in a forEach. This eliminates the guard entirely:

objects.allObjects                           // Add `.lazy` if you don’t want to build the intermediary array
    .compactMap { $0 as? SomeTypeOfObject }
    .forEach { $0.subObject(subObject, objectStateChanged: changedState) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...