困难类型迅速

时间:2018-12-13 10:56:13

标签: swift struct enums tuples

我正在尝试创建一种“难度”类型,该类型可以采用3种状态:容易,中等或困难。然后,将自动设置一个“最小值”和“最大值”值,并且可以像“ myDifficultyInstance.min”或其他内容一样访问。

我尝试了此方法,但不起作用,出现错误:

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

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

有一个简单的解决方案吗?

2 个答案:

答案 0 :(得分:3)

  

枚举时不允许使用默认参数

定义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

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

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) 
}

答案 1 :(得分:1)

我知道您已经接受了答案,但是如果您想同时进行预设和可自定义的难度设置,建议您这样做:

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