Fast programming style

I saw some source code on github, for example: functional-swift

We see that the structure definition is called Ship, and there is some kind of variable in it. The following code shows that it also has some functions. It is written in the following style:

struct xxx { } extension xxx { func yyy() {} } 

I can also define the structure in the following style:

 struct xxx { func yyy() {} } 

So what are the different of the two styles? Is there a quick guide to the programming style?

+6
source share
2 answers

from your example, the first one is the base structure with the extension

 struct xxx { } extension xxx { function yyy() {} } 

the other is a structure with a built-in function.

 struct xxx { function yyy() {} } 

Imagine for some reason you cannot change the original structure, but you still want to be able to execute the yyy () → function, you can extend the class to call the yyy () function, without changing the class itself (or changing the path it behaves elsewhere in your program)

"Extensions can add new functions to a type, but they cannot override existing functions." (src: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html )

-> Extensions are useful if you do not have access to the class, but you want to add some functions. Using extensions, you can separate classes and customize what the class can do as needed.

+1
source

From Swift docs :

Extensions add new features 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 the usefulness of this is when you want to extend an existing implementation. Apple has excellent documentation, and I highly recommend that you read the link above.

0
source

All Articles