Why are types defined with extension?

I'm looking through the swift stdlib code and I notice so much of the code for the built-in types, such as Bool are defined as extensions:
https://github.com/apple/swift/blob/master/stdlib/public/core/Bool.swift

Why is that? Why not just put all of the functionality into the main struct starting at line 64?

Replies

It is a common practice to define in extension and not directly in the struct or the class.

Goal is to keep code more modular and separate the basic definition to more advanced.
And that let declare var that conform to extension, so that they access only this part and not the basic struct.

See Protocols and Extensions
Extrait de: Apple Inc. « The Swift Programming Language  » Apple Books.

That is often used to conform to a Protocol.
Thanks Claude, I re-read the section on Extensions and this is what it says at the top of that section:

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

So Apple obviously has the source code, that's not why they're doing it. I see how each protocol is a separate extension, that makes sense to me too. But I also see that each operator is also an extension. How does that help?

But I also see that each operator is also an extension. How does that help?



That's seems to be because each extension conforms to a different protocol.
Note that you probably do it routinely.

When you subclass UIViewController and need to use tableView, you can declare all protocols at once:

Code Block
class MyViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { }


You can also declare as extensions:

Code Block
class MyViewController: UIViewController { }
extension MyViewController: UITextFieldDelegate { }
extension MyViewController: UITableViewDelegate { }
extension MyViewController: UITableViewDataSource { }

That's very interesting, so you can actually put the UITextFieldDelegate code in it's own section of the file so it is all logically grouped together. I'll try that next time.