gpt4 book ai didi

swift - 如何访问在 Swift 中作为参数传递的二级嵌套枚举

转载 作者:行者123 更新时间:2023-12-04 03:40:43 25 4
gpt4 key购买 nike

尝试访问 Swift 中作为参数传入第一个枚举的双嵌套枚举的值。我不确定如何访问 CutStyle;在 shareSaladfor 循环中,迭代的每个 ingredient 没有 .dot 访问器,除了 self 。 IE。没有可用的 ingredient.cutingredient(cut)

我对如何访问 CutStyle 感到困惑

import Cocoa

enum Ingredients {
case lettuce(cut: CutStyle)
case tomatoes(cut: CutStyle)
case onions(cut: CutStyle)
case cucumbers(cut: CutStyle)
case dressing

enum CutStyle {
case diced
case chopped
case minced
case grated
}
}

var salad: [Ingredients] = []

func makeSalad(with ingredient: Ingredients) {
switch ingredient {
case .lettuce(let cut):
salad.append(.lettuce(cut: cut))
case .tomatoes(let cut):
salad.append(.tomatoes(cut: cut))
case .onions(let cut):
salad.append(.onions(cut: cut))
case .cucumbers(let cut):
salad.append(.cucumbers(cut: cut))
case .dressing(let cut):
salad.append(.dressing(cut: cut))
}
}

func shareSalad(my salad: [Ingredients]) {
print("My salad contains:")
for ingredient in salad {

// Q: How to access the ingredient CutStyle here?
print(ingredient)
}
}

makeSalad(with: .cucumbers(cut: .chopped))
makeSalad(with: .onions(cut: .diced))
makeSalad(with: .tomatoes(cut: .minced))

shareSalad(my: salad)

/*
My salad contains:
cucumbers(cut: __lldb_expr_29.Ingredients.CutStyle.chopped)
onions(cut: __lldb_expr_29.Ingredients.CutStyle.diced)
tomatoes(cut: __lldb_expr_29.Ingredients.CutStyle.minced)
*/

最佳答案

你需要一个巨大的 switch 语句来提取剪切样式,

for ingredient in salad {
let cutStyle: CutStyle?
switch ingredient {
case .lettuce(let cut):
cutStyle = cut
case .tomatoes(let cut):
cutStyle = cut
case .onions(let cut):
cutStyle = cut
case .cucumbers(let cut):
cutStyle = cut
case .dressing:
cutStyle = nil
}
print(cutStyle)
}

我认为你可以更好地模拟你的沙拉。这里有两种可供选择的设计,可让您更轻松地访问剪裁样式。

一种方法是创建一个 SaladIngredient 结构,该结构包含切割样式和配料:

struct SaladIngredient {
enum Ingredient {
case lettuce
case tomatoes
case onions
case cucumbers
case dressing
}

enum CutStyle {
case diced
case chopped
case minced
case grated
}

let ingredient: Ingredient
let cutStyle: CutStyle?
}
func shareSalad(my salad: [SaladIngredient]) {
print("My salad contains:")
for ingredient in salad {
if let cutStyle = ingredient.cutStyle {
print(cutStyle)
}
}
}

这样做的缺点是更难执行敷料没有剪裁样式的规则。

或者,将所有这些具有剪切样式的枚举案例折叠成一个案例:

enum SaladIngredient {
enum Ingredient {
case lettuce
case tomatoes
case onions
case cucumbers
}
enum CutStyle {
case diced
case chopped
case minced
case grated
}
case cuttable(Ingredient, cutStyle: CutStyle)
case dressing
}
func shareSalad(my salad: [SaladIngredient]) {
print("My salad contains:")
for ingredient in salad {
if case .cuttable(_, cutStyle: let cutStyle) = ingredient {
print(cutStyle)
}
}
}

这样做的缺点是您正在使 .dressing 成为与生菜、西红柿和其他食物完全不同的“类型”。

关于swift - 如何访问在 Swift 中作为参数传递的二级嵌套枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66072839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com