I am new to Swift and not very experienced as a programmer in general. My question is what am I doing wrong with decoding data?
I seem to have no problem encoding and writing data to disk but when I read and decode that same data, it is having a problem.
import Foundation
class Person: Codable {
var name: String
init(name: String){
self.name = name
}
}
let aPerson = Person(name: "John")
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let archiveURL = documentsDirectory.appendingPathComponent("name_test").appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedPerson = try? propertyListEncoder.encode(aPerson)
try? encodedPerson?.write(to: archiveURL)
let propertyListDecoder = PropertyListDecoder()
if let retrievedPersonData = try? Data(contentsOf: archiveURL),
let decodedPerson = try? propertyListDecoder.decode(Person.self, from: retrievedPersonData) {
print(decodedPerson)
}
The output is: __lldb_expr_X.Person
(where X is an odd number that will start at 1 and rise after every subsequent run).
Any ideas?
Change line 24 into
print(decodedPerson.name)
decodedPerson is the whole struct. So you need to access to the property itself.
in playground (I suppose that's where you tested), you'll get
decodedPerson John
instead of
__lldb_expr_17.Person
Would be the same with more complex struct:
class Person: Codable {
var name: String
var age: Int
init(name: String, age: Int){
self.name = name
self.age = age
}
}
let aPerson = Person(name: "John Apple", age: 32)
print(decodedPerson)
print("decodedPerson", decodedPerson.name, decodedPerson.age)
will return (here from an app)
AppName.Person
decodedPerson John Apple 32