Rajesh
Rajesh

Reputation: 556

Subclassing vs Extension in 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 !

Upvotes: 15

Views: 7940

Answers (2)

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9925

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

Upvotes: 1

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

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.

Upvotes: 63

Related Questions