Reputation: 448
I am looking for advice to save my array of structures, so they are available at start and can be easily accessed and updated.
All tutorials I have watched have only 1 instance of struct, so I keep failing on implementing array of structures.
Structure of data is:
struct Stock : Codable {
let ticker : String
let amount : Double
var boughtAt : Double
var totalValue : Double
var realTimePrice : Double
var float : Double
var type : String
}
var stocksArray = [Stock]()
Upvotes: 1
Views: 1209
Reputation: 24341
Since your struct Stock
conforms to Codable
, you can easily store the array [Stock]
in UserDefaults
as data
using JSONEncoder
, i.e.
var stocksArray = [Stock]()
do {
let data = try JSONEncoder().encode(stocksArray)
UserDefaults.standard.set(data, forKey: "stocksArray")
} catch {
print(error)
}
Similarly, you can fetch from UserDefaults
using JSONDecoder
like,
if let data = UserDefaults.standard.data(forKey: "stocksArray") {
do {
let arr = try JSONDecoder().decode([Stock].self, from: data)
print(arr)
} catch {
print(error)
}
}
This is one way to store your array
. There are other ways as well - CoreData
, File
etc.
Upvotes: 2
Reputation: 1272
In my opinion, You can convert your Struct to Dictionary type and add that dictionary in to NSArray and save that array to Document directory of phone.
Example,
struct Stock {
var ticker : String = ""
var amount : Double = 0.0
var boughtAt : Double = 0.0
var totalValue : Double = 0.0
var realTimePrice : Double = 0.0
var float : Double = 0.0
var type : String = ""
var json:Dictionary<String,Any> {
set{
self.ticker = newValue["ticker"] as! String
self.amount = newValue["amount"] as! Double
self.boughtAt = newValue["boughtAt"] as! Double
self.totalValue = newValue["totalValue"] as! Double
self.realTimePrice = newValue["realTimePrice"] as! Double
self.float = newValue["float"] as! Double
self.type = newValue["type"] as! String
}
get {
return ["ticker":self.ticker,"amount":self.amount,"boughtAt":self.boughtAt,"totalValue":self.totalValue,"realTimePrice":self.realTimePrice,"float":self.float,"type":self.type]
}
}
init(withJSON json:Dictionary<String,Any>) {
self.json = json
}
}
//Now, get dictionary from object and add it into array.
let stock = Stock(withJSON: [:])
let json = self.stock.json
let array = NSArray(arrayLiteral: json)
//Now, you can save NSArray to file.
array.write(toFile: "file path.plist", atomically: true)
//You can get array from plist file,
let array = NSArray(contentsOfFile: "file path.plist")
Upvotes: 0