Reputation: 9471
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?
Upvotes: 0
Views: 92
Reputation: 63272
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.
Upvotes: 0
Reputation: 1633
It's Protocol-Oriented Programming
, here is some useful links: https://developer.apple.com/videos/play/wwdc2015/408/
https://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-2
Upvotes: 1
Reputation: 229
One use not mentioned: adding to source code you don't have access to.
Upvotes: 1
Reputation: 59496
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.
Upvotes: 4
Reputation: 1595
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.
Upvotes: 2