15

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 !

Rajesh
  • 546
  • 9
  • 29
  • 2
    **You should explain what you want to do**. Some things can be done with inheritance but not with extensions, and other things make sense with extensions but not using inheritance. Your question "as is" is too much generic. There's no answer to your question, pretty much as there's no smart answer to the question "what's better, a car or an helicopter"? – Antonio Jul 02 '15 at 08:59
  • any code, example, what exactly you want to modify in textfield behaviour? – Maxim Shoustin Jul 02 '15 at 08:59

2 Answers2

62

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.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • Excellent answer. You mean if we write an extension *then* every other viewcontroller where ever it may be will see that? Do we have to use any 'public', 'internal' attribute or something? – mfaani Jun 10 '16 at 15:18
  • @Honey It depends on the scope you need: where do you need to use the `extension`? – notsoux Jan 03 '18 at 13:51
1

Swift extensions can't be overridden. So If you would like to create a testing purpose subclasses then you will be limited.

Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93