问题
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
回答1:
We can't add the stored properties
to extensions
directly but we can have the computed variables
.
Extensions in Swift can:
- Add computed instance properties and computed type properties
- Define instance methods and type methods
- Provide new initializers
- Define subscripts
- Define and use new nested types
- Make an existing type conform to a protocol
For more please visit
https://docs.swift.org/swift-book/LanguageGuide/Extensions.html
回答2:
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"
}
回答3:
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
回答4:
You can try ( This is a readOnly computed property )
extension UIViewController {
var someProperty : String {
return "xyz"
}
}
来源:https://stackoverflow.com/questions/52972231/how-to-add-variable-in-existing-class-in-swift