Switchary 0.1.2

Switchary 0.1.2

测试已测试
语言 SwiftSwift
许可证 MIT
发布最后发布2016年1月
SPM支持 SPM

Jo Albright 维护。



Switchary 0.1.2

一个简单的库,用于创建一个具有条件运算符变换的 switch 语句的赋值

使用

要运行示例项目,克隆仓库,然后首先从 Example 目录运行 pod install

enum AgeGroup: Int { case Baby, Toddler, Kid, Preteen, Teen, Adult }

enum LifeStatus: Int { case Alive, Dead, Zombie }

let life: LifeStatus? = .Zombie

现在我们的变量准备好了,我们可以玩一下这些特性。

首先,我想向您展示我之前是如何编写 switch 赋值的。这是可以接受的,但我不想满足于可以接受。

// embedded ternary operators ... old way of writing it

let _ = life == .Alive ? UIColor.yellowColor()
      : life == .Dead ? UIColor.redColor()
      : life == .Zombie ? UIColor.grayColor()
      : UIColor.greenColor()

内联 Switchary 赋值使这个代码更加易于阅读。

// Switchary assignment inline

// ??? starts the switch
// ||| seperates the cases
// *** is our default value

let _ = life ??? .Alive --> UIColor.yellowColor()
             ||| .Dead --> UIColor.redColor()
             ||| .Zombie --> UIColor.grayColor()
             *** UIColor.greenColor()
// Switchary Range

let _ = 21 ??? (0...3) --> AgeGroup.Baby
           ||| (4...12) --> AgeGroup.Kid
           ||| (13...19) --> AgeGroup.Teen
           *** AgeGroup.Adult

目前我只支持内联赋值中的范围、枚举和基本类型。但我想要支持所有类型的模式匹配。这个闭包赋值让你可以传递一个值来匹配,并返回一个要分配的值。

// Switchary closure

let _ = life ??? {

    switch $0 {

    case .Alive: return UIColor.greenColor()
    case .Dead: return UIColor.redColor()
    case .Zombie: return UIColor.grayColor()

    }

}

let _ = 12 ??? {

    switch $0 {

    case 0..<10: return UIColor.clearColor()
    case let x where x < 20: return UIColor.yellowColor()
    case let x where x < 30: return UIColor.orangeColor()
    case let x where x < 40: return UIColor.redColor()
    default: return UIColor.whiteColor()

    }

}

最后,有一个初始化器协议 SwitchInit,它接受一个值和一个初始化器内部的闭包。这允许根据传入的值进行简单的自定义初始化。

// Switchary Initalizer

extension UIView: SwitchInit { }

let button = UIButton (life) {

    switch $0 {

    case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
    case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
    case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)

    }

}   

TBH:我还没有找到这个特性的一个好用途。

安装

Switchary 可通过 CocoaPods 获得。要安装它,只需在 Podfile 中添加以下行

pod "Switchary"

Switchary 也可通过 Swift Package Manager 获得。请查看链接了解如何使用 SPM 的更多信息。

import PackageDescription

let package = Package(
    name: "YOUR_PACKAGE_NAME",
    dependencies: [
        .Package(url: "https://github.com/joalbright/Switchary.git", majorVersion: 0)
    ]
)

作者

Jo Albright

许可证

Switchary 可以在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。