Search code examples
jsonswiftlet

Cannot assign to property: 'desc' is a 'let' constant


I have a problem with an error described in the title - "Cannot assign to property: 'desc' is a 'let' constant".

I would like to assign a string variable to 'desc' in a JSON file. JSON was previously downloaded to a variable named "result".

I have followed by answers for similar questions, but I can't apply resolution to my code.

Class:

import UIKit

class informationViewController: UIViewController {

    //values received from previous view
    var semesterNumber:String?
    var dayNumber:String?
    var text_desc:String?
    var result:Data1!
    var numberRow:Int?

Function:

func saveToJsonFile(result2 : inout Data1) {

        result?.data[Int(semesterNumber!)!].monday[numberRow!].desc = "cos" //Error: Cannot assign to property: 'desc' is a 'let' constant
        
        //Coninue of exectution....
        

Function call:

 @IBAction func isSaveClicked(_ sender: Any) {
        saveToJsonFile(result2 : &result!)
    }

Errors messages


Solution

  •     class infoViewController: UIViewController {
            
            var result:Data1!
            
            override func viewDidLoad() {
                saveToJsonFile(result2 : &result!)
            }
            
            func saveToJsonFile(result2 : inout Data1) {
                result2.data[1].monday[1].desc = "cos"
            }
        }
        
        struct Data1{
            var data: [Monday]
        }
        struct Monday {
            var monday: [Desc]
        }
        struct Desc{
            let desc: String
        }
    

    If you try as above you will get "Cannot assign to property: 'desc' is a 'let' constant" error. So you need to change the let into var, because let is immutable.

    class infoViewController: UIViewController {
                
                var result:Data1!
                
                override func viewDidLoad() {
                    saveToJsonFile(result2 : &result!)
                }
                
                func saveToJsonFile(result2 : inout Data1) {
                    result2.data[1].monday[1].desc = "cos"
                }
            }
            
            
            struct Data1{
                var data: [Monday]
            }
            struct Monday {
                var monday: [Desc]
               
            }
            struct Desc{
                var desc: String
            }