当前位置: 首页 > 知识库问答 >
问题:

无法将“Int”类型的值转换为预期的参数类型“String”?

澹台衡
2023-03-14

我正在保存所有数据,代码写在单独的类中。它显示了一个错误,即无法将类型为“Int”的值转换为预期的参数类型“字符串”。请帮我解决这个问题。

以下是我保存所有数据的类:

class FetchedLocations
{
    var id: Int
    var companyID: Int
    var username: String
    var name: String
    var imei: String
    var created_at: String
    var updated_at: String
    var module_id: Int
    var location_address: String?
    var guard_name: String?
    var guard_contact: String?
    var device: Int?
    var expire_on: Int?
    var status: Int

    init(id: Int, companyID: Int, username: String, name: String, imei: String, created_at: String, updated_at: String, module_id: Int, location_address: String, guard_name: String, guard_contact: String, device: Int, expire_on: Int, status: Int) {

        self.id = id
        self.companyID = companyID
        self.username = username
        self.name = name
        self.imei = imei
        self.created_at = created_at
        self.updated_at = updated_at
        self.module_id = module_id
        self.location_address = location_address
        self.guard_name = guard_name
        self.guard_contact = guard_contact
        self.device = device
        self.expire_on = expire_on
        self.status = status
    }
}

这是ViewController.swift文件:

for eachDepartment in json["locations"]! {
    let eachData = eachDepartment as! [String: Any]
    let id = eachData["id"] as! Int
    let companyID = eachData["company_id"] as! Int
    let username = eachData["username"] as! String
    let locName = eachData["name"] as! String
    let imei = eachData["imei"] as! String
    let createdDate = eachData["created_at"] as! String
    let updatedDate = eachData["updated_at"] as! String
    let moduleID = eachData["module_id"] as! Int
    let locationAddress = eachData["location_address"] as! String
    let guardName = eachData["guard_name"] as! String
    let guardContact = eachData["guard_contact"] as! String
    //let device = eachData["device"] as! Int
    let device = 0
    //let expireOn = eachData["expire_on"] as! Int
    let expireOn = 0
    //let status = eachData["status"] as! Int
    let status = eachData["status"] as! Int

    Date.formatter(createdDate: createdDate)

    //Error encountered in this line//
    FetchedLocations.init(id: id, companyID: companyID, username: username, name: locName, imei: imei, created_at: createdDate, updated_at: updatedDate, module_id: moduleID, location_address: locationAddress, guard_name: guardName, guard_contact: guardContact, device: device, expire_on: expireOn, status: status)

}

遇到错误:

无法将“Int”类型的值转换为预期的参数类型“String”

共有2个答案

凌善
2023-03-14

只需使用另一个变量。

例如,尝试:

让stringFromIntToString=String(您的IntVariable)

这应该没问题。

季城
2023-03-14

试试这个

let a: Int = 5
let str = String(a)

您可以使用codable解析数据https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

 类似资料: