Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 533
guru Avatar asked Oct 24 '18 15:10

guru


4 Answers

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

like image 83
Sateesh Yemireddi Avatar answered Oct 16 '22 06:10

Sateesh Yemireddi


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"
}
like image 31
Harsh Avatar answered Oct 16 '22 07:10

Harsh


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

like image 4
Mahgol Fa Avatar answered Oct 16 '22 05:10

Mahgol Fa


You can try ( This is a readOnly computed property )

extension UIViewController {

    var someProperty : String {

        return "xyz"
    }
}
like image 3
Sh_Khan Avatar answered Oct 16 '22 05:10

Sh_Khan