Convert Realm list of Strings to Array of Strings in Swift
Asked Answered
G

4

7

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

Gerstein answered 6/6, 2019 at 23:26 Comment(1)
Can you show what code you've tried and include the Realm Object you're using? There could be a number of answers and those may or not be correct depending on your use case so to accurately answer can you describe what you're trying to do. Also, please take a moment and review How do I ask a good question? and How to create a Minimal, Complete, and Verifiable example. Update your question, include your code and we'll take a look.Centriole
O
14

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)
Over answered 7/6, 2019 at 7:49 Comment(0)
G
0

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.

Gasman answered 6/6, 2019 at 23:38 Comment(4)
Thank you. I would prefer to keep the list, but it doesn't work, so unfortunately this is what I'm going to have to do.Gerstein
This array of strings is the value in a dictionary, and it doesn't let me have a dictionary of type [Int: List<String>]Gerstein
That almost sounds like a modelable type. Maybe it could be represented as an array of objects, with an int id and list of strings. Difficult to guess without knowing more of the problem. I'd suggest you mark this as answered, and consider asking another question about modelling this (or carry on anyway).Gasman
@Gargo What does that mean? What doesn't work? What 'custom classes' are you talking about, and how is that relevant to the question?Gasman
S
0

Here are the details. how to assign an array in the realm list model.

jim.dogs.append(objectsIn: someDogs)
Subtropical answered 10/3, 2021 at 11:49 Comment(0)
M
0

If you had any other problems such as compiler telling you that you need add operations: to your realm closure, make sure that you are converting List<String>, NOT List<String>?. Do proper if let unwrapping at least so it stops being optional and it will work. Hope that helps.

The error

Maxilliped answered 26/9, 2024 at 11:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.