简体   繁体   中英

Swift Extensions

I am curious as to what is the purpose of writing extensions for a class that you can already add code?

For example, in Ray Wenderlich's AlamoFire tutorial,

He has a ViewController class, but he writes an extension for that ViewController for his Networking Functions and UIImagePickerControllerDelegate methods. Is the only reason he is writing extensions is for the purpose of dividing up code into logical bits?

Is this a common practice or just personal preference?

This is something Apple does too. If you look at the code (let's say the Array struct) you can see that every conformance to a protocol is encapsulated inside an extension.

The only difference is that your code is better separated. But it really is up to you.

I am not sure if it common practice, but I know that I do it because it creates compartmentalized of code. If you need something you just go to the designated extension. However, I believe it is just personal preference.

未提及一种用途:将您无权访问的源代码添加到源代码中。

This is a convention, one which Apple personally follows.

Personally I like it a lot, as it allows you to break up large monolithic classes into smaller, more manageable parts.

In particular, making extensions to separate protocol conformances makes your code a lot more readable. It serves a similar purpose as the #pragma mark preprocessor macro in Objective-C.

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