Subclassing vs Extension in swift

后端 未结 2 701
慢半拍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.

提交回复
热议问题