How to create swift class for category?

Khawar picture Khawar · Jun 10, 2014 · Viewed 62k times · Source

I want to create category of my existing swift class, but there is no option in IDE to do so.

Any idea if category exists in swift project? Or how to achieve similar functionality in swift project?

Answer

Cezar picture Cezar · Jun 10, 2014

In Swift, you can use Extensions to add new functionality to existing classes, structs and enumeration types.

They differ from Objective-C categories in a few ways, mainly:

  • They aren't named
  • You don't need to import an Extension explicitly. If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.
  • As stated above, they work not only with classes, but with other types as well.

As it stands today, Extensions can:

  • Add computed properties and computed static properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

The basic syntax to declare an extension is as follows:

extension SomeType {
    // new functionality to add to SomeType goes here
}

Check Apple's documentation for more information on how to use Extensions in Swift.