简体   繁体   中英

Best practices for extensions of Types in swift

I have been using extensions a lot in my projects because of the level of customisation which I find delightful. They work neatly - so no worries there.

I you want to make an extension on your class, normally you would declare it just outside the class, but in the same file .

If I in want to make an extension on a Type like 'Array' then I would declare the extension outside of the class, but in the same file where I need the extended functionality. However, this extended functionality of 'Array' will now be available in all files in my project.

My question is: If I know I will need some extended functionality in the entire project, is there any good/bad practices in terms if where I declare this extension?

My concern is that when using the new functionality in other files in the project, they may have to create a reference to the file where the extension is declared. Although I have no idea about how this actually works. Just trying to make sure I'm not unintentionally interconnecting all files with a particular viewcontroller/model or likewise.

在此处输入图片说明 I usually don't implement extension anywhere across ViewControllers because if 5 VCs need 5 different extension functionalitis for an Array then we have to write extension Array { } in 5 VCs which will make it hard to navigate and find the implementation for extended functionalities. So what I actually do is make an Extension folder in project hierarcy Where I will make a file named Array+Extension.swift. All the functions releted to array extension will go inside Array+Extension file. The above image will give you a clear picture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM