0

i know that the extension is for to extend types for which you do not have access to the original source code but some developers use extension in a class that themselves make it .

sorry for my english :(

example :

class Category: Mappable {
     var PostCategoryId: Int?
     var Name: String?
     private(set) var Slug: String?
     private(set) var PostCategoryParentId: Int?
     private(set) var PostCategoryParentPath: String?
     var childCategories: [Category]?
     var parentCategory: Category?

     init() {

     }

}

extension Category {

     enum CategoryId: Int {

      case Comedy = 4
      case Action = 6
      case Animation = 10
     }
}
Farhad Faramarzi
  • 425
  • 5
  • 15
  • 1
    Sometimes it is used only for readability. E.g. when I conform to new protocol I can do it with extension and have clean code. – eMKa Aug 03 '16 at 09:17
  • In your case it doesnt realy help you. I use them only if i have a class somewhere else in a libary i didnt allowed to edit so i can add a function to the class with extensions. Or when you need to edit a swift class you can add your own function with extension. – ahdgfd Aug 03 '16 at 09:20
  • 1
    This is not a duplicate. The other question asks specifically about extensions on classes, whereas this question is more general and could include protocol extensions. – Lew Aug 03 '16 at 10:18

2 Answers2

1

One use I find can be useful for separating your own logic from methods which must be implemented when conforming to a protocol. Example:

class MyClass {
  // My custom logic
}

extension MyClass : SomeProtocol {
  // Implement protocol methods here
}

This is purely a code organisation trick but I find it helps to keep things more maintainable.

Another example is for defining default implementations of protocol methods using extensions on protocols. An example:

protocol Askable {
    func ask() -> Int
}

extension Askable {
    func ask() -> Int {
        return 0
    }
}

I'm sure there are some other uses developers have come up with so I'm looking forward to some of the other answers here.

Lew
  • 1,248
  • 8
  • 13
-1

Can be useful when a view has a certain set of functionality, with other classes extending that functionality, but also having some other optional functionality that subclasses can choose to use or not (which is the extension)

An example maybe is to have an extension that implements some delegate methods that could be reused in subclasses, maybe a tableview in a uiviewcontroller that subclasses may or may not have, and if the subclass does have the tableview then they can use the extension instead of rewriting the code for the delegate methods (if its always going to be the same code)

Fonix
  • 11,447
  • 3
  • 45
  • 74