Storing arrays of string persistently in SwiftUI using AppStorage - arrays

I'm trying to store an array of string in user defaults using the AppStorage property wrapper like this:
#AppStorage("History") var history: [String] = ["End of history"]
however I get the error No exact matches in call to initializer
Is this a limitation of AppStorage because UserDefaults can store arrays if I'm not wrong? What is a workaround I can use?

Related

inserting json object into already existing json object inside of a json array

lets say I have a json array called arr, which contains some number of json objects, jsobj1, jsboj2,... jsbojn. if I want to add a new json object jsobjm inside of jsobj2 how would I do that?
I tried to do arr.get(1).put("jsobjm", jsobjm), but I get the error cannot find symbol, pointing to the . before the put().
Well you could do this (instead of manipulating the array as a String):
Convert the JSON array into it's object equivalent and add the object you want using the programming language you use.
Convert the object back to JSON
eg using Javascript
let arr = '[{\"name\":\"Ford\"}]';
//convert to object
let objArray = JSON.parse(arr);
let obj = objArray[0];
//add the other object you want into the first object
obj.description = {"reason":"My fav car"};
console.log(obj);
//convert everything back to string
console.log(JSON.stringify(obj));
JSfiddle: https://jsfiddle.net/allkenang/tuvxrgj3/8/

Kotlin Array with named parameter equivalent of swift

Hi i'am new to Kotlin and i would like to do an array with named parameter. In Swift i can do :
let analytics = ["organization_login": "toto", "organization_name": "titi", "lead_email": "tata"]
The type is : [String: String]
I Looked all Array and Arraylist in kotlin but i couln't find the equivalent.
What i want it's to be able to give parameter name for my array.
Edit
I misunderstood the swift syntaxe, it's seem that it's only a dictonary, so we just have to use map.
The reason is that [String: String] is not an array, it's a Dictionary.
The equivalent of Dictionary in Kotlin is Map.
Maps can be created like so:
val map = mapOf("string_one" to "string_2", "string_3" to "string_4")
or, if you want to mutate it:
val mutableMap = mutableMapOf("string_one" to "string_2")
You need to use Map as
val map = mapOf("organization_login" to "toto", "organization_name" to "titi")
// immutable map
you can also use sortedMapOf, hashMapOf linkedMapOf etc for different algo based storage.
Note: If you want to add more elements later then make sure to use mutableMapOf

Realm object in array?

Question
How can I create an array of objects containing Realm objects?
Code
let realm = try! Realm()
let data: [A] = realm.objects(A)
Error
Cannot invoke 'objects' with an argument list of type '(Object.type)'
How can I create an array of objects containing Realm objects?
From your code sample, I'll further assume that you want to make an array from a Realm Results, not just "standalone" Realm objects.
Since Results conforms to SequenceType, you can use SequenceType.map() to convert it into an array:
let arrayFromResults = results.map({ $0 })
Note, however, that this is almost always the wrong pattern to use.
From your tweet on the same topic, a preferable way to do this would be to encode what you want to display on screen as a Realm query:
self.results = realm.objects(A).filter("poppedOff == NO")
And "popping off" an object (whatever that means) would update the poppedOff property of that object.
Since Realm Results are auto-updating, this won't risk getting out of sync with the contents of the Realm, unlike the array conversion approach, which would have to be updated on every Realm change notification.

Parse.com Query with swift 1.2 and string array

I am trying to query from parse.com and I would db receiving about 100 objects per time. I used the swift example code on their website, and the app doesn't build with that code. So I looked around and found that people were using code similar to this:
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
// do something
self.myDataArray = objects as! [String]
})
This does not work, because I am trying to convert PFObject to String
I would need to get the one one value from each object into a swift string array [String]. How do I get just the one text value, instead of the PFObject and how do I get it into the swift string array?
I don't speak swift very well, but the problem with the code is it's trying to cast the returned PFObject to a string, but you want to extract a string attribute, so (if you really want to do it):
for object in objects {
var someString = object.valueForKey("someAttributeName") as String
self.myDataArray.addObject(someString)
}
But please make sure you need to do this. I've noticed a lot of new parse/swift users (especially those who are populating tables) have the urge to discard the returned PFObjects in favor of just one of their attributes. Consider keeping the PFObjects and extracting the attributes later as you need them. You might find you'll need other attributes, too.
For starters, I would definitely recommend using the "if let" pattern to qualify your incoming data. This is a nice Swift feature that will help avoid run-time errors.
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock(
{ (objects: [AnyObject]?, error: NSError?) -> Void in
// check your incoming data and try to cast to array of "posts" objects.
if let foundPosts = objects as? [posts]
{
// iterate over posts and try to extract the attribute you're after
for post in foundPosts
{
// this won't crash if the value is nil
if let foundString = post.objectForKey("keyForStringYouWant") as? String
{
// found a good data value and was able to cast to string, add it to your array!
self.myDataArray.addObject(foundString)
}
}
})

Is it possible to store an Array into an EncryptedLocalStore item? AIR

I want to save my Array's strucure and load it the next time I open my AIR application. Is there a way to store it to an EncryptedLocalStore item then get it later when I re-open the app?
EncryptedLocalStore.setItem() method takes a byte array when storing contents. To store an array, just use ByteArray.writeObject() method (as described in http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#writeObject()) to convert your Array to a ByteArray - and then persist the same to the ELS.
var array:Array = getArray();
var byteArray:ByteArray = new ByteArray();
byteArray.writeObject(array);
EncryptedLocalStore.setItem('somekey', byteArray);
Hope this helps.
Update: Added code to retrieve the array back.
var byteArray:ByteArray = EncryptedLocalStore.getItem('somekey');
var array:Array = byteArray.readObject() as Array;
Update: For custom classes.
In case you want to serialize your own custom classes to the ByteArray, you may have to call registerClassAlias() before writing the object to the ByteArray. For eg.
registerClassAlias("com.example.eg", ExampleClass);
I have found that it is easiest to to serialize the Array to a string and then store that string in the ELS. Then when you pull it out deserialize it back into an Array.

Resources