【问题标题】:swift enums w Objective-C typedefs in Kotlin在 Kotlin 中快速枚举 w Objective-C typedef
【发布时间】:2018-11-15 22:41:40
【问题描述】:

我正在将一些业务逻辑从 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 种排列。例如:我可以实例化一个 PhotoType,它用 t1 表示 AttachmentType1,用 t2 表示 AttachmentType1,用 t3 表示 AttachmentType1,用 t1 表示 AttachmentType2 等等...

  3. Kotlin 的等效结构是什么? 9 个密封类?

【问题讨论】:

    标签: objective-c swift kotlin enums


    【解决方案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()
    

    ```

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      相关资源
      最近更新 更多