Swift枚举和Kotlin中的Objective-C typedef

时间:2018-11-15 22:41:40

标签: objective-c swift kotlin enums

我正在将一些业务逻辑从iOS迁移到Kotlin,这种构造对我来说很奇怪

// AttachmentType.h
typedef NS_ENUM(NSUInteger, AttachmentType) {
    AttachmentType1 = 0,
    AttachmentType2 = 1,
    AttachmentType3 = 2
}


// PhotoType.swift
enum PhotoType {
    case t1(AttachmentType1), t2(AttachmentType1), t3(AttachmentType1)

    var attachmentType: AttachmentType {
        switch self {
        case .t1(let type):
            return type
        case .t3(let type):
            return type
        case .t3(let type):
            return type
        }
    }
}

我对此感到困惑的是ivar attachmentType

  1. 这实际上是类型AttachmentType的变量吗?

  2. 这样做是否允许两种类型的所有9个排列。例如:我可以实例化一个表示t1的AttachmentType1,t2的AttachmentType1,t3的AttachmentType1,t1的AttachmentType2的PhotoType等等。

  3. Kotlin的等效构造是什么? 9个密封课程?

1 个答案:

答案 0 :(得分:1)

  1. PhotoType使用枚举"associated value"

  2. 它确实允许以类型安全的方式创建9个案例。

  3. Kotlin中的以下结构实现了相同的目标:

```

sealed class PhotoType {
  abstract val type: AttachmentType
}

data class t1(override val type: AttachmentType) : PhotoType()
data class t2(override val type: AttachmentType) : PhotoType()
data class t3(override val type: AttachmentType) : PhotoType()

```