如何在领域中将数组转换为列表? [英] How to convert an array to List in Realm?

查看:60
本文介绍了如何在领域中将数组转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在转换 Realm 类型时遇到问题 List <将jsonData写入Realm时,Int>数组到Int数组[Int].

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)
        }
        }
    }

我试过了,但数组为空

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

我还尝试使用此扩展将列表类型更改为结果并将结果转换为 Int,但它不起作用.

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?

推荐答案

请注意,您的问题不是将 List 转换为数组,而是将数组转换为 List.您已经知道如何执行前者:Array(someList),但是由于您要将数组 (movie.genreIDs ?? []) 分配给 List 属性(movieRealm.genreIDs),需要将数组转换为List.

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.

等等!movieRealm.genreIDs 是一个 let 常量,所以无论如何你都不能分配给它.您真正的问题是您没有正确声明 genreIDs 属性.

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.

如果您遵循 docs 关于如何声明 List 类型的属性:

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>()
}

您将看到不需要将数组转换为 List.您可以将数组的内容添加到 List,因为列表不是 nil:

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 ?? [])

注意,如果你真的想要一个可选列表属性(一个可以为 nil、空或有元素的属性),Realm 不支持.

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.

这篇关于如何在领域中将数组转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆