简体   繁体   English

快速扩展类型的最佳实践

[英]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. 只是要确保我不会无意间将所有文件与特定的viewcontroller / model或类似的对象互连。

在此处输入图片说明 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. 我通常不会在ViewControllers的任何地方实现扩展,因为如果5个VC对一个Array需要5种不同的扩展功能,那么我们必须在5个VC中编写扩展Array {} ,这将使得导航和查找扩展功能的实现变得困难。 So what I actually do is make an Extension folder in project hierarcy Where I will make a file named Array+Extension.swift. 因此,我实际要做的是在项目层次结构中创建一个Extension文件夹,在其中创建一个名为Array + Extension.swift的文件。 All the functions releted to array extension will go inside Array+Extension file. 所有替换为数组扩展名的功能都将放在Array + Extension文件中。 The above image will give you a clear picture. 上面的图像将给您清晰的画面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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