1

Here is my code. I am a beginner using Swift and my code does not work.

Error in view controller was shown:

Cannot assign value of type 'Int' to type 'String'

And:

Could not cast value of type '__NSCFNumber' (0x104061840) to 'NSString' (0x1031324a8). 2019-09-30 01:46:05.056249+0900 Community[20037:815002] Could not cast value of type '__NSCFNumber' (0x104061840) to '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!

    }

Cannot assign value of type 'Int' to type 'String'

on:

vc.post_id = posts[indexPathRow]!["id"] as! Int
2
  • Not directly related to your issue but you should redo your data structure to use a Swift struct instead of dictionary. Commented Sep 29, 2019 at 17:11
  • 1
    what's posts type? Commented Sep 29, 2019 at 17:17

1 Answer 1

1

Please read the error message, it's pretty clear: post_id is declared as String but the dictionary value is an Int

And please conform to the Swift naming convention and name variables lowerCamelCased

Two solutions:

  1. Declare postId as Int

    var postId : Int
    
  2. Create a String from the dictionary value

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

And please conform to the Swift

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.