Convert Realm list of Strings to Array of Strings in Swift

Viewed 6556

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

3 Answers

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