The power of extensions in Swift.

Tram Ho

  • Extension allows us to add functionality to existing type or protocol or some part of the existing Apple SDK library or even components in third party package that we use in the project .
  • However, extension in Swift can be used with many more flexible and advanced ways than just using them to add property or method to external object . In this article, we will study the same uses for them to be used in upcoming project .

1 / Add features to the existing Type:

  • Starting simply have to use extension to add new, custom API for the format type components in Apple system such as the Apple standard library . Specific examples like we need to work on an app whose processing logic requires us to access the element in different arrays, to avoid always having to check the index of the element that we access . We can do the following:

  • Very simple but convenient, right? Now we can use the above method in any Array in the project . Not stopping there we can also make better customizations with the use of extension for the RandomAccessCollection protocol :
  • RandomAccessCollection defines the requests that the collection provides random access to the element . Extending this protocol we will use the new method for any collection including Array :

  • With only the above change, we can now use new method for type like Array , ArraySlice , Range :

  • Using extension for the protocol gives us more flexibility in using the method and property we add.
  • However, not all extension we add are aimed at the above general purpose. In some cases we need additional constraints for specific extension .
  • Let’s look at an example where they add extension to add method help us calculate the total cost of products using the same type constraints to ensure the method will be called only when the Sequence conform type of the Product value:

  • The useful thing of this constraints is that it not only references and guarantees the type for the protocol, but also can be used in the closure as follows:

  • In Swift 5.3, this feature was further upgraded so that we may use this constraints to personalize the method declaration for the types used to encapsulate it.

  • Method on may become useful when we want to pass the same value for the closure such as in the example of the order will notify all observer of Observable type with value changes:

2 / Reorganize APIs and Protocol Compliance:

  • Extension often used in organizing code in project , this is a feature that we have done a lot on Objective-C . We use this to group API with the same functionality that it provides to make it easier to find and rate the functionality.
  • In Swift we use the same approach to sort the API by access level . For example, Publish , we have an constructor to build each website in which the Section serves as a type so that the grouped groups must comply with public , internal , and private :

  • In addition to the benefits of organizing the code , we do not have to give the method access level but each API will automatically be provided with the necessary access.
  • The above implementation is completely applicable to the protocol , we can attach the right conditions for each extension we add, for example we create ListViewController conform UITableViewDelegate via extension :

  • Here we simply create wrapper type conditions to conform Equatable to protocol like Equatable and Hashable only if the Wrapped also satisfies the type of the protocol :

3 / Specialize in the use of generics:

  • At the last point, let’s take a look at how extension can be used to specialize general type and protocol for each real-world use case:
  • Like the Sequence and RandomAccessCollection protocol that we have extended for ease of use like some Apple Framework often use generic to make API more secure and extensible. In Combine the publisher are implement to use the Publisher protocol that includes generic types defined for Output or Failure be generated when the Publisher emits.
  • Those generic types allow us to fully implement Combine operator like using Result for the value returned from the publisher emit :

  • Extension on specifies whether we deploy Combine resemble AsyncValue with Output be assign directly to Result :

  • This approach with constraints allows us to take advantage of Swift ‘s powerful network type inference capabilities, as well as the way SwiftUI uses APIs to build display views.
  • For example, when we work on IconView are rendered with predefined icon . To facilitate the creation of a Button including an icon we can add an extension that uses type constraints Label to define the content which the Button is to be render :

  • And now when we use the above API to create Button instance , complier will automatically add a message telling us that we want to use IconView as follows:

Share the news now

Source : Viblo