Without lazy it would execute as follows: let usernames = For example, imagine having an avatar image fetcher that you want to use to fetch avatars for usernames starting with the letter A. Handling output values on the goĪnother benefit of lazy collections is the option to handle output values on the go. You can imagine this can save you from a lot of work if only a few items are used from a big collection. Modifiers like filter and map will only be executed upon requesting an element: print(modifiedLazyNumbers.first!) In fact, the modifiers aren’t getting called at all! This is because we didn’t request any of the numbers yet. LazyMapSequence>, Int>(_base: Swift.LazyFilterSequence>(_base:, _predicate: (Function)), _transform: (Function)) If we would add the lazy keyword to make the array compute modifiers lazily, the outcome would be different: let modifiedLazyNumbers = numbers.lazy Without using the lazy keyword, all items would be processed directly upon creation: var numbers: = Īs you can see, the doubling of the two even numbers happens after all 5 numbers are filtered. The following example shows a collection of numbers in which even numbers are doubled. This can be beneficial in many different cases and prevent doing unneeded work if elements are never being asked in the end.
How to use icollections free#
Get started with 2 free months of their Business Plan (the best one) with code: SWIFTLEE What is a lazy collection?Ī lazy collection postpones calculations until they are actually needed. Increase your application's performance with rich context about errors and slowdowns in your iOS applications. Keep your iOS Applications Performant (and your users happy)