8

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

4
  • 1
    Always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering. Please edit your question Commented Oct 24, 2018 at 15:17
  • 4
    in an extension you can add computed properties only – if you need a new property, inheritance is also your friend. Commented Oct 24, 2018 at 15:17
  • Why downvote?, is it anything wrong? Commented Oct 24, 2018 at 15:30
  • @guru : Take a look at the answer posted below which shows the work around which is being used from years to add a stored property to extension both in Objective-C world and swift world :) Lemme know if its of any help\ Commented Oct 24, 2018 at 16:57

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

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"
}

Comments

4

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

Comments

3

You can try ( This is a readOnly computed property )

extension UIViewController {

    var someProperty : String {

        return "xyz"
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.