2

I'd like to know how to convert the Swift enum just below to Objective-C:

enum MeatTemperature: Int {
    case Rare = 0, MediumRare, Medium, WellDone

    var stringValue: String {
        let temperatures = ["Rare", "Medium Rare", "Medium", "Well Done"]
        return temperatures[self.rawValue]
    }

    var timeModifier: Double {
        let modifier = [0.5, 0.75, 1.0, 1.5]
        return modifier[self.rawValue]
    }
}
Undo
  • 25,519
  • 37
  • 106
  • 129

2 Answers2

1

Simply prefix the enum with @objc

@objc enum MeatTemperature: Int {
    case Rare = 0, MediumRare, Medium, WellDone

    var stringValue: String {
        let temperatures = ["Rare", "Medium Rare", "Medium", "Well Done"]
        return temperatures[self.rawValue]
    }

    var timeModifier: Double {
        let modifier = [0.5, 0.75, 1.0, 1.5]
        return modifier[self.rawValue]
    }
}

Check this - https://developer.apple.com/swift/blog/?id=22

Uttam Sinha
  • 722
  • 6
  • 9
1

Are you asking how to expose a Swift enum to ObjC or how to write ObjC code equivalent to your Swift code? @UttamSinha's answer handles the first, so here's the second.

ObjC doesn't do methods on enums like Swift does. Traditionally, such cases use global functions — and since they're global, you should name them sensibly to avoid collisions.

typedef NS_ENUM(NSInteger, TTMMeatTemperature) {
    TTMMeatTemperatureRare = 0,
    TTMMeatTemperatureMediumRare,
    TTMMeatTemperatureMedium,
    TTMMeatTemperatureMediumWell, // you forgot the way I like my steaks! :)
    TTMMeatTemperatureWellDone,
}

NSString * TTMMeatTemperatureToString(TTMMeatTemperature temp) {
    NSArray *names = @["Rare", @"Medium Rare", @"Medium", @"Medium Well", @"Well Done"];
    return names[temp];
}

NSString * TTMMeatTemperatureTimeModifier(TTMMeatTemperature temp) {
    double modifiers[] = [0.5, 0.75, 1.0, 1.25, 1.5];
    return modifiers[temp];
}

Also, if you expose your Swift enum to ObjC with @objc, that'll only get the type name and its constants, not the associated functions — you'll need another way to access those from ObjC, like making an @objc class with methods that call them.

rickster
  • 124,678
  • 26
  • 272
  • 326