The global function is useful in Swift

Tram Ho

zip ():

The zip function allows us to merge 2 or more arrays into a Sequence of a tuple. Zip very useful we need to repeat two things at once, if not using zip we will have to use For loop and access each index from each array, while using zip allows them to access elements from all arrays.
For example, if we have a user registration form and we want to update textFields to render a list of validation results received from the backend, usually we will do this:

As for zip

dump ():

The dump function is used to print objects. While to print objects, we use syntax like description or debugDescription , dump will print the contents of the object using reflection, giving the first result more sufficient including the levels of that object.

sequence ()

The sequence() function lets us write recursive functions in a nicer syntax. Assuming we change the background color of a subvuew and all its parent views, we will probably use the while loop like this:

In this case, the most effective way to use is sequence() , as the aspect of the method (currentView = currentView?.superview) always the same, we can use sequence() into a for loop like after:

repeatElement() For an object and the given number, the result is that a Sequence can be repeated with the given number of times.

Most types of fish have special initialization as follows:

So why do we use repeatElement ? The reason is because of performance. The return type of repeatElement() is a Sequence Repeated<T> , meaning it does nothing but provide iterative functionality. Assuming we want to replace a specific array of numbers with another one, one way to accomplish this is to use replaceSubrange with another array:

Using [Int](repeating:) with it to initialize an array of buffer does nothing. If you only need an iterative function, then using repeatElement will have better performance.

stride ():

stride() is a function that is added to Swift as a way to create a for loop to be able to ignore certain elements:

Now we can use stride to achieve the purpose as the above code:

Here’s how we can add the concept of “different dates” to the Date object so we can use stride() : (in fact, Date() has implemented the Strideable method)

Other global functions like:
max() : Returns the maximum value of the argument.
min() : Returns the minimum value of the argument.
abs() : Returns the absolute value of the argument.

Reference: https://swiftrocks.com/useful-global-swift-functions

Share the news now

Source : Viblo