【问题标题】:Сannot convert value of type "Obj" to expected argument type 'Obj'Сannot 将“Obj”类型的值转换为预期的参数类型“Obj”
【发布时间】:2021-02-02 08:48:35
【问题描述】:

我有一个来自服务器的数组。

我的问题是当我想将对象添加到 大批。如何解决此问题并使用对象数组 来自服务器??

返回数据示例

[
    {
        "empId": 1970083,
        "empCode": "2007",
        "empName": "Emp Test",
        "monthClosed": 0,
        "monthApproved": 0,
        "approvedDate": 0,
        "employerName": "Name",
        "employerApproval": 1, 
        "employerApprovalDate": "2020-09-02 17:22:51.843"
    },
]

这个结构来接收这个数据

struct GetMonthSummaryObj: Codable {
    
    var empId: Int?
    var empCode: String?
    var empName: String?
    var monthClosed: Int?
    var monthApproved: Int?
    var approvedDate: Int?
    var employerName: String?
    var employerApproval: Int?
    var employerApprovalDate: String?
}

这是 ViewModel 中的一种方法,用于添加来自数组的数据并将其用于表。例如,显示或表格中的单元格数

func setEmployees(employees: [GetMonthSummaryObj?]) {
        employeesList = []
        
        employees.forEach {_ in
            employeesList.append(CloseMonthEmpListItem(employee: employees))


 //Error - Cannot convert value of type '[GetMonthSummaryObj?]' to expected argument type 'GetMonthSummaryObj'
        }
        
    }

在这里我创建了一个数组对象来使用它

class CloseMonthEmpListItem: Equatable, NSCopying {

    var employee: GetMonthSummaryObj

       init(employee: GetMonthSummaryObj) {
           self.employee = employee
         
       }
    static func == (lhs: CloseMonthEmpListItem, rhs: CloseMonthEmpListItem) -> Bool {
        return lhs.employee.empId == rhs.employee.empId
     }
     
     func copy(with zone: NSZone? = nil) -> Any {
         let copy = CloseMonthEmpListItem(employee: employee)
         return copy
     }
}

【问题讨论】:

    标签: ios arrays json swift mvvm


    【解决方案1】:

    这个 init(employee: GetMonthSummaryObj) 接受GetMonthSummaryObj 类型,而你传递[GetMonthSummaryObj?] 这不起作用

    你需要更换

    employees.forEach {_ in
       employeesList.append(CloseMonthEmpListItem(employee: employees)) 
    }
    

    let res = employees.compactMap{ $0 }
    res.forEach { item in
        employeesList.append(CloseMonthEmpListItem(employee:item)) 
    }
    

    let res = employees.compactMap{ $0 }
    employeesList = res.map { CloseMonthEmpListItem(employee:$0) }
    

    【讨论】:

    • 它有帮助,谢谢。但是当我为单元连接 ViewModel 时,也会出现同样的错误。告诉我,我可以立即使用附带的数组,而不是创建另一个 ListItems 吗?
    猜你喜欢
    • 2016-03-21
    • 2021-04-29
    • 2016-07-27
    • 2016-07-02
    • 1970-01-01
    • 2021-05-14
    • 2020-03-01
    • 2016-08-01
    • 2017-02-07
    相关资源
    最近更新 更多