内省的反思和迭代 [英] Introspection and iteration on an Enum

查看:104
本文介绍了内省的反思和迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个代码不能编译,但是它可以编程地找出一个Enum在Swift 2中有多少个case给你一个我想要实现的想法:

 枚举HeaderStyles {

case h1
case h2
case h3
}

在HeaderStyles中的项目{
print(item)
}


解决方案

你可以编写一个提供迭代能力的通用结构。在下面的例子中,枚举原始值必须以0开头(默认情况下是这样做的),并且原始值之间没有间隙(不能有原始值,如缺少0,1,2,3,5 - 4) / p>

  public struct EnumGenerator< T> :GeneratorType,SequenceType {
private let enumInit:Int - > T'
private var i:Int = 0
public mutating func next() - > T' {return enumInit(i ++)}
public init(_ initFunc:Int - > T?){self.enumInit = initFunc}
}

枚举HeaderStyles:Int {
案例h1
案例h2
案例h3
}

为EnumGenerator中的项目(HeaderStyles.init){
print(item)
}


Is it possible to programatically find out how many "cases" an Enum has in Swift 2 and iterate over them?

This code doesn't compile, but it gives yo an idea of what I'm trying to achieve:

enum HeaderStyles{

    case h1
    case h2
    case h3
}

for item in HeaderStyles{
    print(item)
}

解决方案

You can write a generic struct that provide that iteration ability. In example below the enum raw values must start with 0 (it does it by default) and have no gaps between raw values (can't have raw values such as 0,1,2,3,5 -- 4 is missing)

public struct EnumGenerator<T> : GeneratorType, SequenceType {
    private let enumInit: Int -> T?
    private var i: Int = 0
    public mutating func next() -> T? { return enumInit(i++) }
    public init(_ initFunc: Int -> T?){ self.enumInit = initFunc}
}

enum HeaderStyles:Int{
    case h1
    case h2
    case h3
}

for item in EnumGenerator(HeaderStyles.init){
    print(item)
}

这篇关于内省的反思和迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆