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 !
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.
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.
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.
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.
As a general rule of thumb (YMMV):
UITextField
? If so, make an extension. All UITextField
instances can call the new methods.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With