swift无法将类型“ Int”的值分配给类型“ String”

时间:2019-09-29 17:08:58

标签: swift casting

这是我的代码。我是使用Swift的初学者,我的代码无法正常工作。

显示了视图控制器中的错误:

  

无法将类型为“ Int”的值分配为类型为“ String”的

并且:

  

无法将类型'__NSCFNumber'(0x104061840)的值强制转换为'NSString'(0x1031324a8)。   2019-09-30 01:46:05.056249 + 0900 Community [20037:815002]无法将类型'__NSCFNumber'(0x104061840)的值强制转换为'NSString'(0x1031324a8)。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    // getting index of the cell wherein comments button has been pressed
    let indexPathRow = (sender as! UIButton).tag

    // accessing segue we need -> CommentsVC
    if segue.identifier == "CommentsVC" {

        // accessing destination ViewController -> CommentsVC
        let vc = segue.destination as! CommentsVC

        // assigning values to the vars of CommentsVC
        vc.avaImage = avaImageView.image!
        vc.fullnameString = fullnameLable.text!
        vc.dateString = posts[indexPathRow]!["date_created"] as! String

        vc.textString = posts[indexPathRow]!["text"] as! String


        ////////////
        // sending id of the post
        vc.post_id = posts[indexPathRow]!["id"] as! Int


        // sending the image to the CommentsVC
        let indexPath = IndexPath(item: indexPathRow, section: 0)

        guard let cell = tableView.cellForRow(at: indexPath) as? PicCell else {
            return
        }

        vc.pictureImage = cell.pictureImageView.image!

    }
  

无法将类型为“ Int”的值分配为类型为“ String”的

上:

vc.post_id = posts[indexPathRow]!["id"] as! Int

1 个答案:

答案 0 :(得分:1)

阅读错误消息,这很清楚:A被声明为B,但字典值是post_id

请遵循Swift命名约定并命名变量 lowerCamelCased

两种解决方案:

  1. String声明为Int

    postId
  2. 从字典值创建Int

    var postId : Int
    

请遵循Swift