Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

overriding - How to override setter in Swift

A Superclass :

class MySuperView : UIView{
    var aProperty ;
}

A subclass inheritance the super class :

class Subclass : MySuperClass{
    // I want to override the aProperty's setter/getter method
}

I want to override the superclass's property's setter/getter method ,

how to override this method in Swift ? Please help me , thanks .

question from:https://stackoverflow.com/questions/36440631/how-to-override-setter-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What do you want to do with your custom setter? If you want the class to do something before/after the value is set, you can use willSet/didSet:

class TheSuperClass { 
   var aVar = 0 
} 

class SubClass: TheSuperClass { 
     override var aVar: Int { 
         willSet { 
            print("WillSet aVar to (newValue) from (aVar)") 
        } 
        didSet { 
            print("didSet aVar to (aVar) from (oldValue)") 
        } 
    } 
} 


let aSub = SubClass()
aSub.aVar = 5

Console Output:

WillSet aVar to 5 from 0

didSet aVar to 5 from 0

If, however, you want to completely change how the setter interacts with the superclass:

class SecondSubClass: TheSuperClass { 
     override var aVar: Int { 
        get {
            return super.aVar
        }
        set { 
            print("Would have set aVar to (newValue) from (aVar)") 
        } 
    } 
} 

let secondSub = SecondSubClass()
print(secondSub.aVar)
secondSub.aVar = 5
print(secondSub.aVar)

Console output:

0

Would have set aVar to 5 from 0

0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...