首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在目标C中表示具有关联值的枚举

在目标C中表示具有关联值的枚举
EN

Stack Overflow用户
提问于 2019-11-20 16:21:06
回答 1查看 738关注 0票数 0

Swift中有一些具有相关值的枚举:

代码语言:javascript
复制
enum Coffee {
    case Black
    case BlackWithSugar(spoons: Int)
    // ....
}

很明显,这里的目标是:

  • 有一个表示BlackWithSugar (不是100种情况,如BlackWith1SugarBlackWith2Sugar等)的情况,例如
  • ,但是在相同的结构

中保留额外的信息(勺子数量)。

在目标C中,最接近/最优雅的表达方式是什么?

注意:我看到了this的问题,但两个答案并没有说明如何在目标C中表达相同的意图。我不介意使用其他的东西,而使用Swift不是一种选择。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-20 18:12:36

虽然可以通过大量的工作来完成与Swift在Objective中的关联类型类似的枚举(请参阅我在上面的评论中链接的博客文章),但它需要一堆难以理解的代码。

我建议采取一种更自然的目标-C风格的方法。您可能会失去Swift提供的一些类型安全,但是ObjC自然是一种类型安全较低的语言。

例如:

代码语言:javascript
复制
// 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的优点:

代码语言:javascript
复制
let cm = CoffeeMachine()
cm.makeCoffee(options: [.withSugar, .withCream], quantities: [.spoonsOfSugar : 3])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58958953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档