Bernard
Bernard

Reputation: 4590

How to use enum instead of three different states?

I have three states for two booleans:

_shouldViewMoveUp = true
_shouldViewMoveDown = false

_shouldViewMoveUp = false
_shouldViewMoveDown = false

_shouldViewMoveUp = false
_shouldViewMoveDown = true

We need to track for both boolean variables wether is false/true when there is changes in the keyword frame. I want to design my code to look better.

I'm not sure how to do it with enum or one boolean. Can you explain how I can make my code tidy or just the way it is right?

Upvotes: 1

Views: 90

Answers (2)

trojanfoe
trojanfoe

Reputation: 122429

Define the enum in the header:

typedef NS_ENUM(NSUInteger, MoveDirection) {
    MOVE_NOWHERE,
    MOVE_UP,
    MOVE_DOWN
};

then simply use it where you would use any other primitive; for example:

- (void)moveInDirection:(MoveDirection)direction
{
    switch (direction) {
        case MOVE_UP:
             // move up
             break;
        case MOVE_DOWN:
             // move down
             break;
        default:
             break;
    }
}

or:

@property (nonatomic, assign) MoveDirection moveDirection;

Upvotes: 8

Cy-4AH
Cy-4AH

Reputation: 4585

You can use NSNumber for storing direction.

Fox example:

@property (nonatomic) NSNumber *movedDown;


if (nil == self.movedDown) {
// not moved anywhere
} else if (self.movedDown.boolValue) {
// is moved down
} else {
// is moved up
}

when moved, you assign @YES or @NO

when not moved: nil

Upvotes: 0

Related Questions