Is there anything in Objective-C similar to C# yield return

前端 未结 2 1491
孤街浪徒
孤街浪徒 2021-01-14 08:22

is there anything in Objective-C similar to C# yield return?

相关标签:
2条回答
  • 2021-01-14 08:50

    No, there is nothing in Objective-C that would let you built an iterable solution that easily.

    In general, fast enumeration in Objective-C is built using an entirely different mechanism from C#, Java, or C++. Adopting the protocol is relatively complex, especially compared to C# with its yield return, though it is certainly doable.

    I found that Objective-C blocks provide a usable alternative to fast enumeration. Consider implementing a block-based enumeration instead of fast enumeration - it lets you program your own API using the style similar to yield return. On the flip side, the clients of your API would need to supply a block to use your enumeration. This is not ideal, but usable, especially for complex enumerators, such as ones based on trees.

    0 讨论(0)
  • 2021-01-14 08:55

    There isn't directly and, as dasblinkenlight mentions, fast enumeration exists, but is quite a bit different.

    Mike Ash took this question on in 2009 and came up with an implementation of generators (similar concept):

    http://www.mikeash.com/pyblog/friday-qa-2009-10-30-generators-in-objective-c.html

    Pretty neat bit of runtime wizardry, but I wouldn't necessarily suggest adopting it simply because it enables design patterns that are quite alien to the underlying system; the maintenance and learning curve costs will be pretty steep for use in a production environment.

    0 讨论(0)
提交回复
热议问题