要实现一个枚举 SPORT
,其中包含两个运动类型 SPORT_SKIP_ROPE
和 SPORT_SIT_UP
,并能够根据选中的运动返回对应 JSON 文件的路径,以及读取本地的 JSON 文件以返回 SkipRopeData
或 SitUpData
结构体,可以按照以下方式实现:
import Foundation
// MARK: Define the SPORT enum
enum SPORT: String, CaseIterable {
case SKIP_ROPE = "skip_rope"
case SIT_UP = "sit_up"
var jsonFilePath: String? {
switch self {
case .SKIP_ROPE:
return Bundle.main.path(forResource: "skip_rope", ofType: "json")
case .SIT_UP:
return Bundle.main.path(forResource: "sit_up", ofType: "json")
}
}
func loadData() -> Codable? {
guard let path = jsonFilePath else { return nil }
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
switch self {
case .SKIP_ROPE:
let skipRopeData = try JSONDecoder().decode(SkipRopeData.self, from: data)
return skipRopeData
case .SIT_UP:
let sitUpData = try JSONDecoder().decode(SitUpData.self, from: data)
return sitUpData
}
} catch {
print("Error loading data for \(self.rawValue): \(error)")
return nil
}
}
}
// 使用示例:
if let sportSelected = SPORT(rawValue: "skip_rope") {
if let filePath = sportSelected.jsonFilePath {
print("JSON file path for selected sport is \(filePath)")
if let loadedData = sportSelected.loadData() as? SkipRopeData {
// 在这里处理 SkipRopeData 数据
print("Loaded Skip Rope Data successfully.")
}
}
}
解释:
枚举定义:创建了一个名为
SPORT
的枚举,包含两个案例:SKIP_ROPE
和SIT_UP
。JSON 文件路径:通过计算属性
jsonFilePath
返回对应运动类型的 JSON 文件路径。使用Bundle.main.path(forResource:)
来获取文件路径。加载数据:定义了一个方法
loadData()
,该方法读取对应的 JSON 文件,并将其解码为相应的数据结构(如SkipRopeData
或SitUpData
)。使用了 Swift 的错误处理来捕捉和输出可能发生的错误。使用示例:展示如何选择特定的运动,获取其文件路径,并尝试加载相应的数据结构。
请确保在你的项目中有名为 "skip_rope.json"
和 "sit_up.json"
的文件,以便成功读取和解析。
内容由零声教学AI助手提供,问题来源于学员提问