从字符串获取整数值

时间:2019-03-06 13:30:15

标签: json swift

我收到这样的api响应:

{"id":10,"user_name":"test"}

我能够解析表格视图中的user_name而不出现问题,但ID始终显示为空白

这是我的cellForRowAt函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "userDataCell", for: indexPath) as! UserDataCell
        let userDetails = responseArray[indexPath.row]
        cell.userNameField.text = userDetails["user_name"] as? String
        cell.idTextField.text = userDetails["id"] as? String
        return cell
    }

我想我在获取Int时试图解析字符串的问题

修改为as? Int

cell.idTextField.text = userDetails["id"] as? Int

没有解决问题。有帮助吗?

4 个答案:

答案 0 :(得分:3)

您可以尝试一下作为临时解决方案吗?

cell.idTextField.text = String(userDetails["id"] as? Int ?? 0)

答案 1 :(得分:1)

您可以将字符串安全地转换为整数:

  if let myInt = Int(userDetails["id"] as? String ?? "") {

        }

更新:

cell.idTextField.text = userDetails["id"] as? Int

无论如何,当您将其设置为idTextField时,id必须为String类型而不是Int类型,只需更改以下内容即可:cell.idTextField.text = userDetails["id"] as? String ?? ""

如果要将ID设置为Int,则需要这样设置:

 if let id = Int(userDetails["id"]) {
                cell.idTextField.text = "\(id)"
            }

答案 2 :(得分:1)

我将分两个步骤进行操作,首先尝试获取一个Int,然后分配文本字段以更好地控制分配给文本字段的内容

if let intValue = dict["id"] as? Int {
    cell.idTextField.text = String(intValue)
} else {
    cell.idTextField.text = ""
}

答案 3 :(得分:0)

尝试

cell.idTextField.text = userDetails["id"] as? String ?? userDetails["id"] as? Int ?? "none"