Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChristian A. Castro
30,501 PointsAny idea why I'm receiving this error message in the console!!! Initialization of immutable value 'container', Help!
Error message: Initialization of immutable value 'container' was never used; consider replacing with assignment to '_' or removing it let container = try decoder.container(keyedBy: CodingKeys.self)
import Foundation
let json = """
{
"name": "Pasan",
"id": 1,
"role": "Teacher"
}
//Conversting string literal into a data object with utf8
""".data(using: .utf8)!
struct Employee: Codable
{
let name: String
let id: Int
let role: String
enum CodingKeys: String, CodingKey
{
//Providing a raw value
case name = "name"
case id = "id"
case role = "role"
}
init (from decoder: Decoder) throws
{
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.id = try container.decode(Int.self, forKey: .id)
self.role = try container.decode(String.self, forKey: .role)
}
}
//We need a decoder to handle decoding the JSON, parsing it and assigning values.
let decoder = JSONDecoder()
//Creating an instance of JSONDecoder
let employee = try! decoder.decode(Employee.self, from: json)
employee.name
employee.role
2 Answers
Brandon Mahoney
iOS Development with Swift Techdegree Graduate 30,149 PointsI tried your code and did not receive that warning. Cmd Q and restart the playground.
Michael Psoinos
8,178 PointsYour comment "//Conversting string literal into a data object with utf8" is inside the json String, so it's not valid JSON.