Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing vs Extension in swift

Tags:

swift

I want to customise one UITextField for some reason. So currently I subclassed it and added few methods.

Instead of that can I use extension over UITextField ? Which is good approach ? Please explain !

like image 242
Rajesh Avatar asked Jul 02 '15 08:07

Rajesh


People also ask

What is difference between subclass and extension in Swift?

The new subclass will inherit all the capabilities of the parent class, but may then be extended to add the missing functionality. Swift extensions provide a useful alternative option to adding functionality to existing classes without the need to create a subclass.

What is Subclassing in Swift?

Subclassing. Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.

What is an extension in Swift?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C.

Why do we use extension in Swift?

Extensions let us add functionality to classes, structs, and more, which is helpful for modifying types we don't own – types that were written by Apple or someone else, for example.


1 Answers

As a general rule of thumb (YMMV):

  • Are you adding general-purpose functionalities that should be available to every UITextField? If so, make an extension. All UITextField instances can call the new methods.
  • Are you adding functionality that should be restricted to special instances of UITextField that you would identify precisely? If so, make a subclass. Only the instances of the subclass can use the new methods.

There are other technical considerations, like extensions can't add fields, for instance.

like image 117
Jean-Philippe Pellet Avatar answered Oct 19 '22 22:10

Jean-Philippe Pellet