【问题标题】:swift Cannot assign value of type 'Int' to type 'String'swift无法将“Int”类型的值分配给“String”类型
【发布时间】:2019-09-29 17:08:58
【问题描述】:

这是我的代码。我是使用 Swift 的初学者,我的代码不起作用。

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

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

还有:

无法将“__NSCFNumber”(0x104061840)类型的值转换为“NSString”(0x1031324a8)。 2019-09-30 01:46:05.056249+0900 社区[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

【问题讨论】:

  • 与您的问题没有直接关系,但您应该重做数据结构以使用 Swift 结构而不是字典。
  • 什么是帖子类型?

标签: swift casting


【解决方案1】:

阅读错误信息,很清楚:post_id 被声明为 String 但字典值是 Int

并且请遵守 Swift 命名约定和命名变量lowerCamelCased

两种解决方案:

  1. postId 声明为Int

    var postId : Int
    
  2. 根据字典值创建String

    vc.postId = String(posts[indexPathRow]!["id"] as! Int)
    

请遵守 Swift

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多