Swift中有一些具有相关值的枚举:
enum Coffee {
case Black
case BlackWithSugar(spoons: Int)
// ....
}很明显,这里的目标是:
BlackWithSugar (不是100种情况,如BlackWith1Sugar、BlackWith2Sugar等)的情况,例如中保留额外的信息(勺子数量)。
在目标C中,最接近/最优雅的表达方式是什么?
注意:我看到了this的问题,但两个答案并没有说明如何在目标C中表达相同的意图。我不介意使用其他的东西,而使用Swift不是一种选择。
谢谢
发布于 2019-11-20 18:12:36
虽然可以通过大量的工作来完成与Swift在Objective中的关联类型类似的枚举(请参阅我在上面的评论中链接的博客文章),但它需要一堆难以理解的代码。
我建议采取一种更自然的目标-C风格的方法。您可能会失去Swift提供的一些类型安全,但是ObjC自然是一种类型安全较低的语言。
例如:
// Create an options enum. Bridges into Swift as an OptionSet
typedef NS_OPTIONS(NSInteger, CoffeeOptions) {
CoffeeOptionsBlack = 0,
CoffeeOptionsWithSugar = 1 << 0,
CoffeeOptionsWithCream = 1 << 1
};
// Create a (non-extensible) string-typed "enum". Bridges into Swift as an enum-style struct with string "raw values"
typedef NSString *CoffeeQuantityKey NS_TYPED_EXTENSIBLE_ENUM;
static CoffeeQuantityKey const CoffeeQuantityKeySpoonsOfSugar = @"SpoonsOfSugar";
static CoffeeQuantityKey const CoffeeQuantityKeyTeaspoonsOfCream = @"TeaspoonsOfCream";
@interface CoffeeMachine : NSObject
- (void)makeCoffeeWithOptions:(CoffeeOptions)options quantities:(NSDictionary<CoffeeQuantityKey, NSNumber *> *)quantities;
@end
@implementation CoffeeMachine
- (void)makeCoffeeWithOptions:(CoffeeOptions)options quantities:(NSDictionary<CoffeeQuantityKey, NSNumber *> *)quantities
{
// Make coffee
if (options & CoffeeOptionsWithSugar) {
NSNumber *sugarAmount = quantities[CoffeeQuantityKeySpoonsOfSugar] ?: @1; // Default to 1 spoon
NSLog(@"Adding %@ spoons of sugar", sugarAmount);
}
if (options & CoffeeOptionsWithCream) {
NSNumber *creamAmount = quantities[CoffeeQuantityKeyTeaspoonsOfCream] ?: @1; // Default to 1 teaspoon
NSLog(@"Adding %@ teaspoons of cream", creamAmount);
}
}
@end这还具有将相对较好地连接到Swift的优点:
let cm = CoffeeMachine()
cm.makeCoffee(options: [.withSugar, .withCream], quantities: [.spoonsOfSugar : 3])https://stackoverflow.com/questions/58958953
复制相似问题