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

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. Commented Jun 7, 2019 at 16:59

4 Answers 4

15

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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.
This array of strings is the value in a dictionary, and it doesn't let me have a dictionary of type [Int: List<String>]
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).
@Gargo What does that mean? What doesn't work? What 'custom classes' are you talking about, and how is that relevant to the question?
0

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

jim.dogs.append(objectsIn: someDogs)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.