# Why are extensions used so heavily?

**URL:** <https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399>\
**Category:** Using Swift\
**Tags:** extension\
**Created:** [March 8, 2020, 11:05pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399 "2020-03-08T23:05:00Z")\
**Posts on this page:** 10\
**Page:** 2

<div class="post-metadata">

**Author:** ![jonprescott](https://avatars.discourse-cdn.com/v4/letter/j/e36b37/32.png) [@jonprescott](https://forums.swift.org/u/jonprescott)\
**Post date:** [March 14, 2020, 6:35am UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/21 "2020-03-14T06:35:21Z")

</div>

Extensions can extend classes, structs, enums, as well as protocols.

---

<div class="post-metadata">

**Author:** ![Swift\_Coder](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/swift_coder/32/31230_2.png) [@Swift\_Coder](https://forums.swift.org/u/Swift_Coder)\
**Post date:** [February 17, 2023, 11:33pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/22 "2023-02-17T23:33:20Z")

</div>

Interesting question. I will bring an example to understand which is the better approach to follow. Do you guys think the following Code is more readable (something more readable to me means it's either more organized, written without too much complexity etc..)

```swift
import Foundation

class CustomerListViewModel {
    
    // MARK: - Public Vars
    var customerHasBeenSelected: ((Customer) -> Void)?
    var loadingDataHasStarted: (() -> Void)?
    var loadingDataHasEnded: (() -> Void)?
    var loadingDataHasFailed: ((Error) -> Void)?
    var reload: (() -> Void)?
    
    // MARK: - Private Vars
    private var customers: [Customer] = []
    private let customerService: CustomerService
    
    // MARK: - Init
    init(customerService: CustomerService) {
        self.customerService = customerService
    }
    
}

// MARK: - Input Methods
extension CustomerListViewModel {
    
    func customerSelected(at index: Int) {
        let customerSelected = customers[index]
        customerHasBeenSelected?(customerSelected)
    }
    
}

// MARK: - Support Methods
extension CustomerListViewModel {
    
    func numberOfCustomers() -> Int {
        return customers.count
    }
    
    func makeCustomerTableViewCellViewModel(at index: Int) -> CustomerTableViewCellViewModel {
        let customer = customers[index]
        return CustomerTableViewCellViewModel(customer: customer)
    }
    
}

// MARK: - Services
extension CustomerListViewModel {
    
    func loadCustomers() {
        loadingDataHasStarted?()
        customerService.customers { [weak self] response in
            self?.loadingDataHasEnded?()
            switch response {
            case .failure(let error):
                self?.loadingDataHasFailed?(error)
            case .success(let customers):
                self?.customers = customers
            }
            self?.reload?()
        }
    }
    
}

```

---

<div class="post-metadata">

**Author:** ![idrougge](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/idrougge/32/3885_2.png) [@idrougge](https://forums.swift.org/u/idrougge)\
**Post date:** [February 17, 2023, 11:38pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/23 "2023-02-17T23:38:47Z")

</div>

I think the `// MARK:` delineations already serve the purpose of splitting the file into categories, the extensions themselves do not add much.

Two recurring patterns I see in use of extensions in the same file as the extended object are:  
a) Conformances to protocols. This means they can be easily extracted into files or types of their own.  
b) A main declaration that only contains stored properties and possibly initialisers, with methods being defined in an additional extension. This ensures that the methods do not add extra stored properties and thereby remain reasonably "pure".

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [February 18, 2023, 12:24am UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/24 "2023-02-18T00:24:25Z")

</div>

> [@idrougge](#):
>
> I think the `// MARK:` delineations already serve the purpose of splitting the file into categories, the extensions themselves do not add much.

not everyone uses xcode 🙂

and moreover extensions can do a lot of things MARKs can't. you can add `@available` to an extension. you can use them to gate APIs en masse by generic constraint. today you can even index them with SymbolGraphGen, which means in theory you could attach documentation to them.

---

<div class="post-metadata">

**Author:** ![idrougge](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/idrougge/32/3885_2.png) [@idrougge](https://forums.swift.org/u/idrougge)\
**Post date:** [February 18, 2023, 12:25am UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/25 "2023-02-18T00:25:23Z")

</div>

Good point, though I hope other editors support `MARK` too.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [February 18, 2023, 2:41am UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/26 "2023-02-18T02:41:45Z")

</div>

> [@Jon\_Shier](#):
>
> Extensions are “trendy” in Swift because they’re trivial to add compared to categories in Objective-C.
> 
> Edit: Plus they’re far more useful as well, as retroactive conformance wasn’t really a thing in Obj-C.

I wonder why you say so. A trivial example showing both extension (category) and retroactive conformance in Objective-C:

```swift
#import <UIKit/UIKit.h>

@interface MyView: UIView
@end

@implementation MyView
@end

// MARK: example category
@implementation MyView (SomeCategory)
- (void)foo { printf("Hello\n"); }
@end

// MARK: example category conforming to a protocol
@interface MyView (Datasource) <UITableViewDataSource>
@end

@implementation MyView (Datasource)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 10;
}
...
@end

```

Just a few more characters to type compared to Swift, but that's the case for pretty much everything in Obj-C compared to Swift.

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [February 18, 2023, 6:01am UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/27 "2023-02-18T06:01:15Z")

</div>

That's not a retroactive conformance, just a conformance of your type to a protocol in a category. That wasn't super common, but was used to conform large types to protocols. I don't recall if Obj-C supported fully retroactive conformance (a type you don't own conforming to a protocol you don't own) but I largely meant it wasn't popular. Whether that was due to the language itself or just the community I'm not sure.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [February 18, 2023, 1:55pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/28 "2023-02-18T13:55:21Z")

</div>

> [@Jon\_Shier](#):
>
> I don't recall if Obj-C supported fully retroactive conformance (a type you don't own conforming to a protocol you don't own) but I largely meant it wasn't popular. Whether that was due to the language itself or just the community I'm not sure.

That's possible as well:

```swift
// MARK: example category conforming to an existing protocol
@interface UIView (Datasource) <UITableViewDataSource>
@end

@implementation UIView (Datasource)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 10;
}
@end

@protocol MyProto
- (void)bar;
@end

// MARK: example category conforming to a custom protocol
@interface UIView (MyProto) <MyProto>
@end

@implementation UIView (MyProto)
- (void)bar {}
@end

```

IIRC protocols and categories themselves were relatively new addition to Objective-C 10 years ago (I remember I had to lobby using categories back then in the project I was working at the time).

---

<div class="post-metadata">

**Author:** ![tevamerlin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tevamerlin/32/2152_2.png) [@tevamerlin](https://forums.swift.org/u/tevamerlin)\
**Post date:** [February 18, 2023, 3:52pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/29 "2023-02-18T15:52:33Z")

</div>

> [@tera](#):
>
> IIRC protocols and categories themselves were relatively new addition to Objective-C 10 years ago (I remember I had to lobby using categories back then in the project I was working at the time).

I remember loving protocols and categories when I learned Objective C more than 20 years ago — and they were not recent additions even back then.

My guess is that if you had to lobby for them 10 years ago, it may have been because of the flood of new Objective C programmers after the introduction of iOS, who were not used to categories and most likely tended to use them a lot less than MacOS app developers did before that (and NeXTStep devs before them).

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [February 18, 2023, 5:34pm UTC](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399/30 "2023-02-18T17:34:04Z")

</div>

You are [right](http://andrewd.ces.clemson.edu/courses/cpsc102/notes/ObjC.pdf). IIRC the main objection was along the lines of usage of the -ObjC flag in the library, for some reason the guys were afraid of using it (the fear that client apps would be reluctant adding that). Indeed that was for iOS.

[Previous page](https://forums.swift.org/t/why-are-extensions-used-so-heavily/34399.md?page=1)
