【问题标题】:How to implement an enum and switch statement in Swift based on properties that change?如何根据变化的属性在 Swift 中实现枚举和 switch 语句?
【发布时间】:2015-08-20 15:41:10
【问题描述】:

我正在尝试在我的代码中实现一些逻辑,以提供一个“门”,以根据应用内购买来连接到另一个 VC。

当用户点击添加按钮时,我想要 3 个可能的结果:

(1) 如果用户购买了 IAP,segue, (2) 如果用户没有购买但 var x = 1,不要segue并显示alert view

以下是我认为应该如何在 Swift 中进行设置,但是我不确定如何将我想要的值放入我的枚举中?什么在 Swift 中最有效?

enum Access {

    case Purchased  //a bool true or false
    case AddOne  // not purchased but people < 1
    case Locked //not purchased and people >= 1

}

switch Access {

    case .Purchased: // segue
    case .AddOne: // segue
    case .Locked: // alertView

}

【问题讨论】:

    标签: ios swift enums switch-statement


    【解决方案1】:

    根据您的描述,可能不需要enum

    class MyViewController : UIViewController {
      var purchased = false
      var people = 0
    
      @IBAction func handleButton (UIButton button) {
        if purchased {
          // segue
        }
        else if people < 1 {
          // segue
        }
        else {
          // alertView
        }
      }
    }
    

    或者,如果您已经从 (purchased, people) 映射到枚举,则使用 enum

    class MyViewController : UIViewController {
      var access : Access = .Purchased
    
      @IBAction func handleButton (UIButton button) {
        switch access {
        case .Purchased:
          // segue
        case .AddOne:
          // segue
        case .Locked:
          // alert
        }
      }
    }
    

    【讨论】:

    • 我曾想避免使用 if 语句来支持 enum/switch 方法,认为这将是更有效的选择,但您的代码演示了 if 语句是多么简单。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多