Swift UITableView 自定义单元格单复选标记错误

我正在尝试使用自定义单元格在UITableview中的时间创建单一复选标记。  我正在使用下面的代码,但报错了

Binary operator '==' cannot be applied to operands of type 'Project?' and 'Project'

项目中使用的代码

我的Struct

struct ProjectRoot: Codable {
    let status: Bool
    let data: ProjectClass
}

// MARK: - DataClass
struct ProjectClass: Codable {
    let projects: [Project]
}

struct Project: Codable {
    let id: Int
    let projectName: String
    let date: String

    enum CodingKeys: String, CodingKey {
        case id
        case projectName = "project_name"
        case date = "date"
    }
}

我的代码

// Tableview Data Load
    var filteredData = [Project]()

    var selectedProject:Project? {
        get {
            if let data = UserDefaults.standard.value(forKey: "selectproject") as? Data,
                let storeProject = try? JSONDecoder().decode(Project.self, from: data) {
                return storeProject
            }
            return nil
        }
        set {
            if let data = try? JSONEncoder().encode(newValue) {
                UserDefaults.standard.set(data, forKey: "selectproject")
            }
        }
    }

Tableview Delegate

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:ProjectCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! ProjectCustomCell
        //configure you cell here.
        if selectedProject == filteredData[indexPath.row] { // Here, I am getting error
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }

        return cell
    }

原来解决这个错误,发现Equatable需要继承Equatable

struct Project: Codable, Equatable {
    let id: Int
    let projectName: String
    let date: String

    enum CodingKeys: String, CodingKey {
        case id
        case projectName = "project_name"
        case date = "date"
    }

    static func == (lhs: Project, rhs: Project) -> Bool {
        //lhs stands for left hand side, rhs for right hand side.
        return lhs.id == rhs.id
    }
}
if let selectedProj = selectedProject, selectedProj == filteredData[indexPath.row] {
    cell.accessoryType = .checkmark
} else {
    cell.accessoryType = .none
}
我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章