Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef enum Objective-C

I have class Distance and typedef enum Unit,

@interface Distance:NSObject{

double m_miles;

}

@property double m_miles;

-(Distance *) initWithDistance: (double) value andUnit:(Unit) unit;

@implementation Distance

-(Distance *)initWithDistance: (double) value andUnit:(Unit) unit{

  self = [super init];

 if (self){

   switch (unit) {

     case Unit.miles:  m_miles = value;

                       break;

    case Unit.km:      m_miles = value/1.609344;

                       break;
}


}

Where do I declare my enum Unit? How to access

typedef enum{

    miles;

    km;

}Unit

In the other class I should be able to call Distance.Unit.km or miles:

Distance *a = [[Distance alloc] initWithDistance: 10.2 andUnit: Distance.Unit.km];
like image 484
Ravit Teja Avatar asked Dec 05 '25 20:12

Ravit Teja


2 Answers

In C an enum doesn't makes its values "qualified". You have to access it with

Distance *a = [[Distance alloc] initWithDistance: 10.2 andUnit:km];
//                                                             ^^
//                                                             no Distance.Unit.stuff
like image 185
kennytm Avatar answered Dec 08 '25 14:12

kennytm


It looks like you are trying to do a class typedef like you can in say C++. I don't remember if that is even allowed in Objective-C but thats not how I would do it here anyway. I would keep the enum outside of the class. Just create another header file with the typedef. Though this is sort of a trivial example, there may be other uses for that enum outside of the Distance class so define it outside.

Another possibility, if this is all you are using it for is to have two initializers initWithMiles: and initWithKilometers:.

like image 24
JeffW Avatar answered Dec 08 '25 13:12

JeffW