Search code examples
arraysjsonparsingstructswift3

Can not insert a string from json in a property struct


I did create a struct GetData in which there is a func callAlamofire. I do the call to the url and get the data in the console without problems. My problem is assigning a string I did obtain after parsing to a property of the Dato struct. I have an error "Cannot assign to property: 'name' is a 'let' constant". This error is in the last written code

self.dato.name = self.name

I pretend to create an array datos of the Struct, then call it all in the ViewController, and from here populate my tableView.`

import Foundation
import Alamofire
struct GetData{
let url = "https://baas.kinvey.com/appdata/kid_W1BkLMHDCx/Contacts/"
let headers = ["Authorization":"Basic a2lkX1cxQmtMTUhEQ3g6ZWJiZjVhODg0MGIxNDg5NWFlOTg3YzM3MjIxZDE5NGE=", "Content-Type": "application/x-www-form-urlencoded"]
var dato = Dato(name: "", email: "")
var datos = [Dato]()

func callAlamofire(){
    Alamofire.request(url, method: .get, headers: headers)
        .responseJSON { (data) in
            guard let myJson = data.result.value as? [[String: AnyObject]] else {return}
            for item in myJson{
                if let name = item["name"] as? String{
                    print(name)
                    self.dato.name = self.name
            }
        }
    }
} 

What alternatives can I have to pass the name string to my var dato of Dato struct, so that I can later append it to a datos array? Thanks for the help.


Solution

  • As @vadian said in the comment.

    Your Dato struct has the property name as a let constant.

    Just change it to var.