Abrcd18
Abrcd18

Reputation: 185

How to convert an array to List in 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?

Upvotes: 4

Views: 7619

Answers (3)

XYZ
XYZ

Reputation: 27387

let swiftList = [Date(), Date(), Date()]
let realmList = List<Date>()
realmlist.append(objectsIn: swiftList)

Explicit data type need to be used when initiating the Realm List object.

Upvotes: 0

unferna
unferna

Reputation: 125

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

let yourList = List()
yourList.append(objectsIn: /* your array here */)

Upvotes: 2

Sweeper
Sweeper

Reputation: 271645

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.

Upvotes: 8

Related Questions