Subclassing vs Extension in swift

后端 未结 2 689
慢半拍i
慢半拍i 2021-02-02 16:50

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

相关标签:
2条回答
  • 2021-02-02 17:44

    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.

    0 讨论(0)
  • 2021-02-02 17:47

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

    0 讨论(0)
提交回复
热议问题