Convert Realm list of Strings to Array of Strings in Swift - swift

I'm just starting up with RealmSwift, and I'm trying to store an array of Strings in Realm. It doesn't work, so now I'm using List<String>() as an alternative. However, how do I convert these Realm Lists back to [String] again? And if I can't do that, are there any alternatives?
Thanks

However, how do I convert these Realm Lists back to [String] again
You can simply cast List to Array, because List has Sequence Support:
let list = List<String>()
let array = Array(list)

Bear in mind that by converting to an array you'll lose the 'dynamic' quality of a Realm collection (i.e. you'll receive a static array, whereas keeping the original List will provide automatic updating should the source change). But you can create an array by using an extension, e.g.:-
extension RealmCollection
{
func toArray<T>() ->[T]
{
return self.compactMap{$0 as? T}
}
}
Then use:-
let stringList = object.strings.toArray()
Where object is the realm object, and strings is your field.

Here are the details. how to assign an array in the realm list model.
jim.dogs.append(objectsIn: someDogs)

Related

Realm Swift - Convert an array of results into an array of Ints

I want to convert the results from my Realm data into Int.
Here is an example of how I want to use this.
let results = realm.objects(Data.self)
print(results)
However the result is type Results<Data> and cannot be converted into a Int but the results is an Int.
Just to be clear I want an array of Int from my results
You can simply use Array(realm.objects(RealmType.self)), which will convert the Results<RealmType> instance into an Array<RealmType>.
However, there are other serious flaws with your code. First of all, neither of the last two lines will compile, since firstly realm.objects() accepts a generic input argument of type Object.Type and Data doesn't inherit from Object. You can't directly store Data objects in Realm, you can only store Data as a property of a Realm Object subclass.
Secondly, myArray[results] is simply wrong, since results is supposed to be of type Results<RealmType>, which is a collection, so using it to index an Array cannot work (especially whose Element type is different).
It appears that based on the number of results from the database, you want to select an object from the array.
You can get the number of items in an array with .count. Be certain that an object exists at the specified index in the array, or your application will crash!
let numberOfResults = results.count
if myArray.count > numberOfResults {
let object = myArray[numberOfResults]
print(object)
}

Dictionary data structure returns nil in Swift

I am trying to implement a dictionary data structure in swift that stores an Array of Strings. I have declared it like:
var journeyDetails = [Int: [String]]()
When I want to append an actual string to it, I do
if let journeys = fetchedData["journeys"] as? [[String: Any]]{
var nr_of_journey : Int = 0
for journey in journeys{
self.journeyDetails[nr_of_journey]?.append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
}
}
nr_of_journey = nr_of_journey + 1
etc etc. However, journeyDetails keeps returning nil. Should I do any other type of initialization? Why is the data not appended?
Initially there are no keys or values in journeyDetails so every use of self.journeyDetails[nr_of_journey] returns nil.
If you are using Swift 4, you can specify a default value to be used if there currently isn't a value for the given key.
Update the line:
self.journeyDetails[nr_of_journey]?.append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
to:
self.journeyDetails[nr_of_journey, default: []].append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
This provides a default empty array if there currently isn't a value for the given nr_of_journey key.

Storing a simple array in Realm without creating a managed List in Swift

I have an array of data that doesn't need to be a managed List, meaning I don't need Realm to create a new model for the items with links and the ability to query on the items, etc. I just want a simple array, typically of primitives that don't inherit from Object anyway, that will be persisted with my main object.
The only solution I can think of is to use NSData and NSKeyedArchiver/NSKeyedUnarchiver. Is that the best/only way to do this? Should I just use List even if I don't think I'll need it — what's the best practice for this situation?
Realm doesn't support arrays of primitives (although that functionality is coming soon), so the most straightforward solution is to use a List filled with model objects that just wrap your primitives. There's nothing wrong with archiving to and from NSData and storing the data in your Realm model, though, if you feel that better suits your particular use case.
Here's how I decided to deal with this:
var instructions: [String] {
get {
if _instructions == nil {
_instructions = NSKeyedUnarchiver.unarchiveObject(with: instructionsData) as? [String]
}
return _instructions!
}
set {
instructionsData = NSKeyedArchiver.archivedData(withRootObject: newValue)
_instructions = newValue
}
}
fileprivate var _instructions: [String]? = nil
dynamic var instructionsData = Data()
override static func ignoredProperties() -> [String] {
return ["instructions", "_instructions"]
}
That way I can use the array as I normally would and still have it persisted in a simple way (without having to create an actual List and having to manage a bunch of new models/objects).

Set<NSObject>' does not have a member named 'allObjects'

With the original swift I could turn an NSSet (e.g. of Strings) into a typed array with the following syntax:
var stringArray = exampleSet.allObjects as [String]
With the new update I am getting the above error. What is the best way now to convert the Set into an array?
It looks as if your exampleSet is not an NSSet but a native
Swift Set which was introduced with Swift 1.2 (compare https://stackoverflow.com/a/28426765/1187415).
In that case you can convert it to an array simply with
let array = Array(exampleSet)
Looks like 'set' is a keyword. Try using a different variable name

Create a mutable array of arrays each containing a dictionary in swift?

I am trying to declare a variable that stores an array of arrays. Each array then contains a Dictionary object. I tried a bunch of different possible declarations but the compiler is not happy with any of them.
Any suggestion?
Thanks
Clarification on what I needed:
An array that contains arrays where each of them contains dictionaries.
You Said
Each array then contains a Dictionary object
that mean that each array will have a single Dictionary so why do you need that extra Array
anyway the following code declare an Array that contain Dictionaries(The code assume that eventually your dictionary will contain strings but you can change that to any type you want)
var myObj = Array<Dictionary<String,String>>()
var dic1:Dictionary<String,String> = Dictionary<String,String>()
dic1["A"] = "Alpha :A"
dic1["B"] = "Alpha :B"
var dic2:Dictionary<String,String> = Dictionary<String,String>()
dic2["C"] = "Alpha :C"
dic2["D"] = "Alpha :D"
myObj.append(dic1)
myObj.append(dic2)
if you need an array containing arrays of dictionaries it will be almost the same
var myObj = Array<Array<Dictionary<String,String>>>()