Swift 枚举实用小 tips

把之前简书上写的搬运过来。


场景一

列表展示枚举数据,用户点击后保存对应的 code 码。

可以结合元组将所有信息放到枚举中:

enum ShoesQuality {
    
    case new
    case flaw
    case dressed
    case secondHand
    
    var info: (desc: String, code: Int) {
        get {
            switch self {
            case .new:
                return ("全新闲置", 100)
            case .flaw:
                return ("全新瑕疵", 200)
            case .dressed:
                return ("轻微穿着", 300)
            case .secondHand:
                return ("二手穿着", 400)
            }
        }
    }
    
}

使用如下,清晰方便:

let alertController = UIAlertController(title: "选择球鞋成色", message: nil, preferredStyle: .actionSheet)
let array: [ShoesQuality] = [.new, .flaw, .dressed, .secondHand]
array.forEach { (quality) in
    let action = UIAlertAction(title: quality.info.desc, style: .default) { (action) in
        self.selectedQualityCode = quality.info.code
    }
    alertController.addAction(action)
}
present(alertController, animated: true, completion: nil)

场景二

用枚举表示支付结果,当支付失败时展示失败原因。

可以使用枚举的关联值进行传值:

/// 支付结果
enum PayResult {
    case succeed                    // 成功
    case failed(errorInfo: String?) // 失败
    case canceled                   // 取消
}

使用:

AlipaySDK.defaultService()?.payOrder(result, fromScheme: SCHEME_STRING, callback: { (resultDict) in
    // 说明
    let desc: String = resultDict!["memo"] as? String ?? ""
    // 状态码
    if let code: String = resultDict!["resultStatus"] as? String {
        switch code {
        case "9000": // 订单支付成功
            completion(.succeed)
        case "4000": // 订单支付失败
            completion(.failed(errorInfo: desc))
        case "6001": // 用户中途取消
            completion(.canceled)
        default:
            completion(.failed(errorInfo: desc))
        }
    }
})

场景三

个人中心页面可以是用户的个人中心也可以是订阅号的个人中心,另外:

  1. 用户的个人中心要区分是本人还是别人,如果是别人,传userID;
  2. 订阅号传subscribeID。

定义:

enum UserDetailType {
    case person(isOwn: Bool, userID: String?) // 个人(是否是自己,userID)
    case subscribe(subscribeID: String)       // 订阅(订阅号ID)
}

使用:

let type = UserDetailType.person(isOwn: false, userID: "001")

switch type {
case .person(isOwn: true, _):
    print("is own")
case .person(isOwn: false, let userID):
    print("is other \(userID ?? "")")
case .subscribe(let subscribeID):
    print("订阅ID:\(subscribeID)")
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祖安狂人学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值