Press ESC to close

Swift Extension

Hello friends. In this article, we will talk about how to use an extension with Swift. First, let’s talk about what is Extension. Extension is actually adding a function or another property to a class or struct or even any object. In this article, I will create an extra function for the String class to explain with an example. With this function I can simply add my own name. You can easily use it in many different areas. Instead of writing separate functions for each class and using them, you can just write an extension and use it everywhere. Afterwards, we will be able to do it more comfortably while refactoring.

I created a playground and made my example here. First, we create a structure called Extension and we need to specify which class or structure this extension will affect. I will add a new function to the String class. Then we add our function and this function returns a string value back. In our function, we can take the current value with self, then I add my own name to this existing value.

import UIKit

extension String {
    func addMyName() -> String {
        return self + "Omer"
var str = "Hello, playground"


In fact, adding extensions is that simple and convenient. The result is as follows.

If you have questions, you can reach by e-mail or comment. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *