【问题标题】:SwiftUI enum String, Codable, Hashable ErrorSwiftUI 枚举字符串,可编码,可散列错误
【发布时间】:2021-11-05 10:05:52
【问题描述】:
import SwiftUI
import Foundation
import Combine
import CoreLocation

struct structuralCodes: Hashable, Codable, Identifiable {
    var id = UUID()
    var index: Int
    var title: String
    var icon: String
    var isFeatured: Bool
    
    var category: Category
    enum Category: String, CaseIterable, Codable, Hashable {
        case asce = "ASCE"
        case aisc = "AISC"
    }
    
    var imageName: String
    var image: Image {
        Image(imageName)
    }
    
}

var structuralcodes = [
    structuralCodes(index: 1, title: "ASCE", icon: "wind", isFeatured: true, category: "ASCE", imageName: "ASCE"),
    structuralCodes(index: 2, title: "AISC", icon: "wind", isFeatured: false, category: "AISC", imageName: "AISC"),
]

import SwiftUI
import Foundation
import Combine

final class ModelData: ObservableObject {

    @Published var choosecodes: [structuralCodes] = structuralcodes
    
    var features: [structuralCodes] {
        structuralcodes.filter { $0.isFeatured }
    }
    
    var categories: [String: [structuralCodes]] {
        Dictionary(
            grouping: choosecodes,
            by: { $0.category.rawValue }
        )
    }
} //: ModelData

我的 var 结构代码中出现错误

(category: "ASCE") //Error Here下第一个引号 (category: "AISC") //Error Here under the first quote

错误显示:

无法将“字符串”类型的值转换为预期的参数类型 'structuralCodes.Category

我想当我有 String 的枚举时,它会将案例保存在 var 类别下,因为我输入了一个字符串。大写和小写都试过了,怎么都报这个错。

【问题讨论】:

  • 为什么不只是category: .asce
  • 你应该发布这个作为答案。

标签: swiftui enums hashable


【解决方案1】:

你可以试试这个:

var structuralcodes = [
    structuralCodes(index: 1, title: "ASCE", icon: "wind", isFeatured: true, category: structuralCodes.Category(rawValue: "ASCE")!, imageName: "ASCE"),
    structuralCodes(index: 2, title: "AISC", icon: "wind", isFeatured: false, category: structuralCodes.Category(rawValue: "AISC")!, imageName: "AISC"),
]

所有Categorys 都是Strings,但并非所有Strings 都是Categorys,这就是为什么你需要在这里跳过箍。强制展开在这里是安全的,因为您明确分配了一个有效的rawValue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多