ComposeUI中的枚举
基本概念
课程代码
https://github.com/BellyBook/ChunxiangClassCode-Android
Kotlin中枚举的基本概念和使用场景。
- Name
枚举定义
- Type
- enum
- Description
- 有限的选项集合
- 类型安全
- 支持属性
- 支持方法
- Name
枚举特性
- Type
- features
- Description
- 可实现接口
- 可定义方法
- 支持扩展函数
- 支持密封类替代
枚举基础示例
// 基础枚举
enum class Direction {
NORTH,
SOUTH,
EAST,
WEST
}
// 带属性的枚举
enum class StatusCode(val code: Int) {
SUCCESS(200),
NOT_FOUND(404),
SERVER_ERROR(500)
}
// 密封类作为枚举替代
sealed class NetworkResult {
data class Success(val data: String): NetworkResult()
data class Error(val exception: Exception): NetworkResult()
}
ComposeUI中的应用
在ComposeUI中使用枚举的常见场景。
- Name
界面状态
- Type
- states
- Description
- 加载状态
- 视图模式
- 导航状态
- 动画状态
- Name
数据处理
- Type
- data
- Description
- 错误处理
- 用户输入
- 数据过滤
- 主题设置
ComposeUI应用示例
// 界面状态枚举
sealed class LoadingState {
object Loading : LoadingState()
object Loaded : LoadingState()
data class Error(val message: String) : LoadingState()
}
@Composable
fun ContentView(state: LoadingState) {
when (state) {
is LoadingState.Loading ->
CircularProgressIndicator()
is LoadingState.Loaded ->
Text("数据加载完成")
is LoadingState.Error ->
Text("错误: ${state.message}")
}
}
高级特性
枚举的高级用法和特性。
- Name
递归枚举
- Type
- recursive
- Description
- indirect关键字
- 数据结构
- 表达式求值
- 树形结构
- Name
模式匹配
- Type
- pattern
- Description
- switch语句
- if case语法
- guard case语法
- 穷尽性检查
高级特性示例
// 递归枚举
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// 模式匹配
enum Message {
case text(String)
case image(URL)
case location(latitude: Double, longitude: Double)
}
let message = Message.location(latitude: 37.7749, longitude: -122.4194)
if case .location(let lat, let lon) = message {
print("位置: \(lat), \(lon)")
}
最佳实践
枚举使用的推荐做法。
- Name
设计原则
- Type
- principles
- Description
- 命名规范
- 单一职责
- 可扩展性
- 类型安全
- Name
常见用例
- Type
- cases
- Description
- 状态管理
- 配置选项
- 错误处理
- API设计
最佳实践示例
// 错误处理
enum AppError: Error {
case networkError(String)
case databaseError(String)
case validationError(field: String, message: String)
}
// 主题设置
enum Theme {
case light
case dark
case system
var backgroundColor: Color {
switch self {
case .light: return .white
case .dark: return .black
case .system: return .clear
}
}
}
// 配置选项
enum SortOrder: String, CaseIterable {
case ascending = "升序"
case descending = "降序"
}