When I am declaring the Array variable as let it works just fine, but when I change the declaration from let to var, instead of taking the default value that is provided(an empty array), it initialises it as nil
import Foundation
struct Model: Codable {
let name: String? = "John"
let data: [String]? = []
}
let data = """
{
"name": "John"
}
""".data(using: .utf8)!
if let myObject = try? JSONDecoder().decode(Model.self, from: data) {
dump(myObject)
}
More on initialized let properties: compare our code above with:
import Foundation
struct Model: Codable {
let name: String? = "John"
let data: [String]? = []
// Compiler error:
// Immutable value 'self.name' may only be initialized once
// Immutable value 'self.data' may only be initialized once
init(name: String?, data: [String]?) {
self.name = name
self.data = data
}
}
Some will advise you to generally prefer var declarations of struct properties, and to rely on variable declarations in order to be guaranteed with immutability:
struct Model {
var name: String? = "John"
var data: [String]? = []
}
// Immutable name and data
let model: Model = ...
You also have private(set) and other language niceties to control mutability.
So... let properties have their use cases, but they can come in the way, as you can see. Maybe consider using them only as a last resort. YMMV.