guru
guru

Reputation: 2817

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

Upvotes: 8

Views: 14613

Answers (4)

Sateesh Yemireddi
Sateesh Yemireddi

Reputation: 4409

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

Upvotes: 7

Mahgolsadat Fathi
Mahgolsadat Fathi

Reputation: 3325

you can only use computed variables: for example we have the type Int in swift, and we want it extend in a way that swift generates a random number from 0 to our number :

extension Int
{
    var arc4random : Int{
        if self > 0
        {return Int(arc4random_uniform(UInt32(UInt(self))))}

         else if self < 0
        {return -Int(arc4random_uniform(UInt32(UInt(abs(self)))))}

        else
        {return 0}
    }
}

and usage :

myArray.count.arc4random

here my array.count is an Int , and arc4random is the computed variable we have defined in our extension, u cant store a value in it

Upvotes: 4

Shehata Gamal
Shehata Gamal

Reputation: 100533

You can try ( This is a readOnly computed property )

extension UIViewController {

    var someProperty : String {

        return "xyz"
    }
}

Upvotes: 3

Harsh
Harsh

Reputation: 2908

You can only add computed properties to extensions as follows...

extension UIViewController {
   var someProperty = "xyz" : String {
      return "xyz"
   }
}

If you wish to use it the way you are defining it, you might need to subclass your UIViewController

class YourCustomViewController: UIViewController {
    var someProperty: String = "xyz"
}

Upvotes: 4

Related Questions