Search code examples
iosswiftextension-methods

How to add variable in existing class in swift?


I know that in swift we can use Extensions to add new methods to existing classes.

But what about if i want to add a variable?

extension UIViewController {

    var myVar = "xyz"
}

It gives like :

Extensions must not contain stored properties


Solution

  • We can't add the stored properties to extensions directly but we can have the computed variables.

    extension UIViewController {
        var myVar: String {
            return "xyz"
        }
    }
    

    Extensions in Swift can:

    • Add computed instance properties and computed type properties
    • ...

    For more please visit

    https://docs.swift.org/swift-book/LanguageGuide/Extensions.html