我正在将一些业务逻辑从 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
这本质上是
AttachmentType
类型的变量吗?这是否允许两种类型的所有 9 种排列。例如:我可以实例化一个 PhotoType 来表示带有 t1 的 AttachmentType1、带有 t2 的 AttachmentType1、带有 t3 的 AttachmentType1、带有 t1 的 AttachmentType2 等等……
Kotlin 的等效结构是什么? 9个密封类?
最佳答案
PhotoType
使用枚举 "associated value"它确实允许以类型安全的方式创建 9 个案例。
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()
```
关于objective-c - 在 Kotlin 中使用 Objective-C typedefs 快速枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53328892/