-1

How can I use a custom struct in NSCache? When I add the User struct to NSCache, I get an error like the image below.

Cache Store:

class QuestionCacheStore {
    let cache = NSCache<NSString, User>()
}

Error:

'NSCache' requires that 'User' be a class type

enter image description here

I am using struct for User model. Do I need to convert my model to class?

Model:

// MARK: - User
struct User: Codable {
    var uid: String
    var questions: UserQuiz
    var wrongQuestions: [UserQuestionList]?
}

// MARK: - UserQuiz
struct UserQuiz: Codable, Hashable {
    var title: String?
    var test: [UserQuestionList]?
}

// MARK: - UserQuestionList
struct UserQuestionList: Codable, Hashable {
    var id: Int?
    var question: String?
    var isQuestionImage, isSectionImage: Bool?
    var imageURL: String?
    var sections: UserQuestionSections?
    var correct: String?
}

// MARK: - UserQuestionSections
struct UserQuestionSections: Codable, Hashable {
    var A, B, C, D: String?

    enum CodingKeys: String, CodingKey {
        case A = "A"
        case B = "B"
        case C = "C"
        case D = "D"
    }
}
Ufuk Köşker
  • 1,288
  • 8
  • 29

1 Answers1

0

Use a box type that encapsulates the User struct inside a class object and store that in the cache instead. It's pretty trivial to write your own, but https://github.com/robrix/Box has an implementation as well.

Rudedog
  • 4,323
  • 1
  • 23
  • 34