【问题标题】:difficult type in swift快速输入困难
【发布时间】:2018-12-13 10:56:12
【问题描述】:

我正在尝试制作一种“难度”类型,它可以采用 3 种状态:简单、中等或困难。然后会自动设置“最小”和“最大”值,并且可以访问,例如“myDifficultyInstance.min”或其他什么。

我试过这个但不起作用,我得到错误:

enum Difficulty {
   case easy(min: 50, max: 200)
   case medium(min: 200, max: 500)
   case hard(min: 500, max: 1000)
}

然后我尝试了一个结构,但它变得太奇怪和丑陋了。

有没有简单的解决方案?

【问题讨论】:

标签: swift struct enums tuples


【解决方案1】:

枚举情况下不允许使用默认参数

当您定义enum 的情况时,您不能定义默认值。想象一下,您只是在创建“模式”。

但你可以做的是,你可以通过创建静态常量来创建默认情况

enum Difficulty {
    case easy(min: Int, max: Int)
    case medium(min: Int, max: Int)
    case hard(min: Int, max: Int)

    static let defaultEasy = easy(min: 50, max: 200)
    static let defaultMedium = medium(min: 200, max: 500)
    static let defaultHard = hard(min: 500, max: 1000)
}

那么你可以这样使用它

Difficulty.defaultEasy
Difficulty.defaultMedium
Difficulty.defaultHard

我还认为,对于您需要获取 minmax 值的情况,如果您使用自定义数据模型会更好

struct Difficulty {

    var min: Int
    var max: Int

    static let easy = Difficulty(min: 50, max: 200)
    static let medium = Difficulty(min: 200, max: 500)
    static let hard = Difficulty(min: 500, max: 1000) 
}

【讨论】:

  • 不错的解决方案! #recursiveEnumerations ;)
  • 不错!那么如果我想访问例如最小值,我该怎么办?
  • @Placard 我不确定您是否可以使用枚举执行此操作,但如果您使用自定义模型Difficulty 会更好
  • @Placard 更新了我的答案,你可以激励自己
  • 完美,正是我想要的!谢谢
【解决方案2】:

我知道你已经接受了一个答案,但如果你想同时拥有预设和可自定义的难度设置,我建议你这样做:

enum Difficulty {
   case easy
   case medium
   case hard
   case custom(min: Int, max: Int)

   var min : Int {
       switch self {
       case .easy:
           return 50
       case .medium:
           return 200
       case .hard:
           return 500
       case .custom(let min,_):
           return min
       }
   }

   var max : Int {
       switch self {
       case .easy:
           return 200
       case .medium:
           return 500
       case .hard:
           return 1000
       case .custom(_,let max):
           return max
       }
   }
}

通过这种方式,您将获得枚举困难(有限排他状态),并可选择定义自定义困难。

用法:

let difficulty : Difficulty = .easy
let customDifficulty : Difficulty = .custom(min: 70, max: 240)

let easyMin = difficulty.min
let easyMax = difficulty.max

let customMin = customDifficulty.min
let customMax = customDifficulty.max

【讨论】:

  • 谢谢,也很完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多