Reading the doc of UserDefaults
:
The UserDefaults class provides convenience methods for accessing
common types such as floats, doubles, integers, Boolean values, and
URLs. These methods are described in Setting Default Values.
A default
object must be a property list—that is, an instance of (or for
collections, a combination of instances of) NSData, NSString,
NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any
other type of object, you should typically archive it to create an
instance of NSData.
The old way (more Objective-C way), is to conforms to NSCoding
. That's a way to transforming from/to ClassA
<-> (NS)Data
.
The "new way", is to use Codable
, which is more Swift, but has some differences from previous solution (it's more "universal", but could have extra steps needed for more "complexes" stuffs).
Since Vehicle
is Codable
, use a Encoder
(usually, JSONEncoder
) to encode it into Data
, and then save it into UserDefaults
, and a Decoder
(usually JSONDecoder
) to retrieve it. But it could be also PlistEncoder
/PlistDecoder
.