What is the purpose of an extension in Swift?
iOS interview question for Intermediate practice.
Answer
Extensions in Swift allow you to add new functionality to existing types without modifying their original implementation. This is incredibly useful for extending the capabilities of built-in types like String, Int, Array, or even your own custom classes and structs. They promote code reusability and prevent modification of existing code, which is crucial for maintaining a clean and well-organized codebase. How to use Extensions: Extensions are declared using the extension keyword, followed by the type you want to extend. Here's a simple example adding a new method to the String type: swift extension String { func trimmed() - String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } } let myString = " Hello, world! \n" let trimmedString = myString.trimmed() // trimmedString will be "Hello, world!" This extension adds a trimmed() method that removes leading and trailing whitespace and newline characters from a string. The self keyword refers to the instance of the String on which the method is called. Extending Protocols: Extensions can also extend protocols. This allows you to provide default implementations for protocol methods, making it easier for conforming types to adopt the protocol. For instance: swift protocol MyProtocol { func doSomething() } extension MyProtocol { func doSomething() { print("Default implementation") } } struct MyStruct: MyProtocol {} let myStruct = MyStruct() myStruct.doSomething() // Prints "Default implementation" Here, the extension provides a default implementation for the doSomething() method. MyStruct, even without explicitly defining doSomething(), can conform to MyProtocol and still function correctly. Best Practices: Keep extensions focused and concise, aiming for a single, well-defined purpose. Avoid creating overly general extensions that might lead to naming conflicts or unexpected behavior. Properly document your extensions to explain their functionality and usage.
Explanation
Extensions in Swift can even add computed properties and subscripts to existing types, further expanding their functionality.