Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

for loop - Swift Functional with Array and a Guard ... Possible?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...