How can I write this typedef enum from object c in swift?
Below, I have objective-c code that is used for tinder style animation effect, inspired by - https://github.com/ngutman/TinderLikeAnimations/tree/master/TinderLikeAnimations .
Objective-c
typedef NS_ENUM(NSUInteger , GGOverlayViewMode) {
GGOverlayViewModeLeft,
GGOverlayViewModeRight
};
- (void)setMode:(GGOverlayViewMode)mode
{
if (_mode == mode) return;
_mode = mode;
if (mode == GGOverlayViewModeLeft) {
self.imageView.image = [UIImage imageNamed:@"button1"];
} else {
self.imageView.image = [UIImage imageNamed:@"button2"];
}
}
I am trying to copy the same thing in swift. This is what I have in the quick -
enum GGOverlayViewMode : Int {
case GGOverlayViewModeLeft
case GGOverlayViewModeRight
}
func setMode(mode: GGOverlayViewMode){
// if (_ mode == mode) {
// return
// }
//
// _mode = mode;
if(mode == GGOverlayViewMode.GGOverlayViewModeLeft) {
imageView.image = UIImage(named: "button1")
} else {
imageView.image = UIImage(named: "button2")
}
}
But somehow it doesn't make sense, how do I handle typdefs here.
Any help is appreciated.
thank
source to share
In Swift, each enumeration has its own member values, so you don't have to prefix them with a unique prefix like in (Objective-) C. A typical definition would be
enum GGOverlayViewMode {
case Left
case Right
}
Also, you don't need to specify a base "raw type" (for example Int
), unless you have other reasons to do so.
Instead of a custom configuration method, you must implement a property observer .
didSet
is called immediately after saving the new value and has an implicit parameter oldValue
containing the old value of the property:
var mode : GGOverlayViewMode = .Right {
didSet {
if mode != oldValue {
switch mode {
case .Left :
imageView.image = UIImage(named: "button1")
case .Right:
imageView.image = UIImage(named: "button2")
}
}
}
}
source to share
I think quickly, your function would look like this.
enum GGOverlayViewMode : Int
{
case GGOverlayViewModeLeft
case GGOverlayViewModeRight
}
func setMode(mode: GGOverlayViewMode){
switch mode
{
case .GGOverlayViewModeLeft:
imageView.image = UIImage(named: "button1")
case .GGOverlayViewModeRight:
imageView.image = UIImage(named: "button2")
}
}