嵌套和关联枚举值 Swift

3
NSHipster推荐处理表格或集合视图时使用枚举来表示每个部分的最佳实践之一,示例如下:
typedef NS_ENUM(NSInteger, SomeSectionType) {
    SomeSectionTypeOne = 0,
    SomeSectionTypeTwo = 1,
    SomeSectionTypeThree = 2
}

这使得编写类似于switch语句或if语句非常容易,例如:

if(indexPath.section == SomeSectionTypeOne) {
    //do something cool
}

对于静态内容的部分,我将概念扩展到每个项目都包括枚举:

typedef NS_ENUM(NSInteger, SectionOneItemType) {
    ItemTypeOne = 0,
    ItemTypeTwo = 1
}

if(indexPath.section == SomeSectionTypeOne) {
     switch(indexPath.item) {
     case SectionOneItemType:
         //do something equally cool
     default:
     }
}

在Swift中,我想要复制相同的行为,但这次利用嵌套枚举。到目前为止,我已经想出了以下内容:
enum PageNumber {
    enum PageOne: Int {
        case Help, About, Payment
    }
    enum PageTwo: Int {
        case Age, Status, Job
    }
    enum PageThree: Int {
        case Information
    }
    case One(PageOne)
    case Two(PageTwo)
    case Three(PageThree)
}

但我不知道如何从一个 NSIndexPath 开始初始化正确的情况,然后使用 switch 语句提取值。

1个回答

0

不要认为你可以使用嵌套枚举来决定单元格来自哪个部分和行。因为在 Swift 枚举中,关联值和原始值不能共存。需要使用多个枚举。

enum sectionType: Int {
    case sectionTypeOne = 0, sectionTypeTwo, sectionTypeThree
}

enum rowTypeInSectionOne: Int {
    case rowTypeOne = 0, rowTypeTwo, rowTypeThree
}

//enum rowTypeInSectionTwo and so on

let indexPath = NSIndexPath(forRow: 0, inSection: 0)

switch (indexPath.section, indexPath.row) {
case (sectionType.sectionTypeOne.rawValue, rowTypeInSectionOne.rowTypeOne.rawValue):
    print("good")
default:
    print("default")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接