Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to List in Realm?

Tags:

swift

realm

I have a problem with converting Realm type List < Int> array to Int array [Int] when writing jsonData to Realm.

 struct Movies: Codable {
        let genreIDs: [Int]?
 }

 class CachedMovies: Object {
      let genreIDs: List<Int>?
 }

 func saveMovies(movies:[Movies]) {
    do {
        let realm = try! Realm()
        try realm.write {
        movies.forEach { (movie) in
            let movieRealm = CachedMovies()
            movieRealm.id = movie.id ?? 0
            movieRealm.title = movie.title ?? ""
            movieRealm.genreIDs = movie.genreIDs ?? [] // here's error: Cannot assign value of type '[Int]?' to type 'List<Int>?'
            realm.add(movieRealm, update: .modified)
        }
        }
    }

I tried this but array comes empty

var newArr = Array(movieRealm.genreIDs)
newArr = movie.genreIDs ?? []

I also tried to change List type to Results and convert Results to Int by using this extension but it's not working.

extension Results {
     func toArray<T>(type: T.Type) -> [T] {
     return compactMap { $0 as ? T }
     }
    }

Could you please help me how can I assign arrays correctly?

like image 622
Abrcd18 Avatar asked Nov 07 '25 17:11

Abrcd18


2 Answers

Note that your problem is not about converting List to array, but rather converting an array to List. You already know how to do the former: Array(someList), but since you are assigning an array (movie.genreIDs ?? []) to a List property (movieRealm.genreIDs), you need to convert an array to a List.

But wait! movieRealm.genreIDs is a let constant, so you can't assign to it anyway. Your real problem is that you haven't declared the genreIDs property correctly.

If you follow the docs on how to declare a property of a List type:

class CachedMovies: Object {
     // genreIDs should not be optional
     let genreIDs = List<Int>()
}

You'll see that you don't need to convert arrays to List. You can just add the contents of the array to the List, since the list is not nil:

movieRealm.genreIDs.append(objectsIn: move.genreIDs ?? [])

Note that if you actually want an optional list property (a property which can be nil, empty, or have elements), Realm doesn't support that.

like image 114
Sweeper Avatar answered Nov 09 '25 08:11

Sweeper


BTW If your purpose is actually to convert an array to a Realm List:

let yourList = List()
yourList.append(objectsIn: /* your array here */)
like image 29
unferna Avatar answered Nov 09 '25 08:11

unferna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!