官术网_书友最值得收藏!

How to do it...

Now, let's imagine that we are working on a game, and you have different types of monsters, and based on the type of monster, you will define power or the difficulty of the game. In that case, you have to use enum to create a monster type with different cases, as follows:

  1. Type the following code to create enum with name Monster:
      enum Monster{ 
        case Lion 
        case Tiger 
        case Bear 
        case Crocs 
      } 
 
      enum Monster2{ 
        case Lion, Tiger, Bear, Crocs 
      } 
  1. Use the '.' operator to create enums variables from the previously created enum:
      var monster1 = Monster.Lion 
      let monster2 = Monster.Tiger 
      monster1 = .Bear 
  1. Use the switch statement to check the value of enum to perform a specific action:
      func monsterPowerFromType(monster:Monster) ->Int { 
    
        var power = 0 
    
        switch monster1 { 
          case .Lion: 
            power = 100 
          case .Tiger: 
            power = 80 
          case .Bear: 
            power  = 90 
          case .Crocs: 
            power = 70 
        } 
        return power 
      } 
 
      let power = monsterPowerFromType(monster1) // 90 
 
      func canMonsterSwim(monster:Monster) ->Bool{ 
    
        switch monster { 
          case .Crocs: 
            return true 
          default: 
            return false 
        } 
      } 
 
      let canSwim = canMonsterSwim(monster1) // false 
主站蜘蛛池模板: 新乡市| 砀山县| 璧山县| 呼和浩特市| 苗栗市| 南皮县| 牙克石市| 定南县| 冕宁县| 宜章县| 城固县| 上蔡县| 东平县| 山东省| 宁国市| 阳曲县| 新余市| 肥乡县| 大足县| 嘉定区| 台中县| 湖北省| 乌苏市| 大渡口区| 伊川县| 哈巴河县| 通许县| 新营市| 洪湖市| 西吉县| 高安市| 军事| 平阴县| 习水县| 库尔勒市| 云和县| 古丈县| 育儿| 台安县| 邵东县| 和硕县|