Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift programming style [duplicate]

Tags:

ios

swift

I saw some source code in github, like this: functional-swift

We can see there's definition of a struct called Ship, and there're some variable in it. From the following code we can see that there're also some function in it. It is written in the following style:

struct xxx {
}

extension xxx {
    func yyy() {}
}

I can also definite the struct in the following style:

struct xxx {
    func yyy() {}
}

So what the different of the two style? Is there a swift programming style guide?

like image 648
leizh00701 Avatar asked Jan 05 '16 08:01

leizh00701


1 Answers

from your example, the first one is a basic struct with an extension

struct xxx {
}

extension xxx {
function yyy() {}
}

the other is a struct with a function built in.

struct xxx {
function yyy() {}
}

imagine you cannot modify the original struct for some reason but you still want to be able to perform function yyy() -> you can extend the class to call the function yyy() without modifying the class itself (or changing the way it behaves elsewhere in your program)

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

-> Extensions are useful when you don't have access to a class but you want to add some functionalities. Using extensions, you can compartmentalize your classes and customize what a class can do as needed.

like image 103
John Avatar answered Oct 13 '22 12:10

John