lfalkau
lfalkau

Reputation: 916

difficult type in swift

I'm trying to make a 'Difficulty' type that can takes 3 states : easy, medium or hard. Then a 'minimum' and 'maximum' values will be set automatically and reachable like "myDifficultyInstance.min" or what.

I tried this but doesn't work, I get errors :

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

Then I tried with a struct but it becomes too weird and ugly.

Is there a simple solution to do that ?

Upvotes: 1

Views: 109

Answers (2)

FruitAddict
FruitAddict

Reputation: 2032

I know you accepted an answer already, but if you want to have both preset and customizable difficulty setting i'd suggest doing it like that:

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

This way you're getting enumerated difficulties (finite exclusive states) with an option to define a custom one.

Usage:

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

Upvotes: 1

Robert Dresler
Robert Dresler

Reputation: 11210

Default arguments are not allowed in enum cases

When you defining cases of enum, you can't define default values. Imagine it as you're just creating "patterns".

But what you can to is, that you can create default cases by creating static constants

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

then you can use it like this

Difficulty.defaultEasy
Difficulty.defaultMedium
Difficulty.defaultHard

Also I think that for your case when you need to get min or max value, would be better if you were using custom data model

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

Upvotes: 3

Related Questions