Where to create and how to use Enum in iOS?
In the enum you've created, s
, m
etc. are now available globally (i.e. to anything that imports sample.h
). If you want the integer corresponding to Saturday, for example, it's just sa
, not days.sa
. I think you're confusing enums with structures.
For this reason, it's better to use more verbose names in your enum. Something like:
typedef enum{ WeekdaySunday = 1, WeekdayMonday, WeekdayTuesday, WeekdayWednesday, WeekdayThursday, WeekdayFriday, WeekdaySaturday} Weekday;
so e.g. WeekdayMonday
is now just another way of writing 2
in your app, but will make your code more readable and pre-defines the possible legal values for a variable of type Weekday
.
The above is fine, but for better compiler support and to ensure the size of a Weekday
, I'd recommend using NS_ENUM
:
typedef NS_ENUM(NSInteger, Weekday){ WeekdaySunday = 1, WeekdayMonday, WeekdayTuesday, WeekdayWednesday, WeekdayThursday, WeekdayFriday, WeekdaySaturday};
hey you use enum like this here is an example
In .h define enum
typedef enum{s=1,m,t,w,th,f,sa} days;
In .m play with enum element like this
days d1 =f; switch (d1) { case m: case t: NSLog(@"You like Tuesday"); break; case w: case th: break; case f: NSLog(@"You like friday"); break; case sa: NSLog(@"You satureday"); break; case s: NSLog(@"You like sunday"); break; default: break; }
if you want learn more click this.
#import <Foundation/Foundation.h> typedef enum{ s=1,m,t,w,th,f,sa} days; @interface weekday : NSObject @property (nonatomic, assign) days day; @end @implementation weekday @end int main(int argc, const char * argv[]) { @autoreleasepool { weekday *sunDay=[[weekday alloc]init]; sunDay.day=s; NSLog(@"Today is %d",sunDay.day); }return 0;}