Search code examples
swiftuienumshashable

SwiftUI enum String, Codable, Hashable Error


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

I get an error in my var structuralcodes on the part

(category: "ASCE") //Error Here under the first quote (category: "AISC") //Error Here under the first quote

The error reads:

Cannot convert value of type 'String' to expected argument type 'structuralCodes.Category

I thought when I had enum for String, it would save the case under var Category since I inputed a String. I have tried uppercase and lowercase, and get this error no matter what.


Solution

  • You can try this:

    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"),
    ]
    

    All Categorys are Strings, but not all Strings are Categorys, that's why you need to jump through the hoops here. And force unwrapping is safe here, because you're clearly assigning a valid rawValue