领域结果对象类型 [英] Realm Results object type

查看:48
本文介绍了领域结果对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的很基础,但是我只是找不到如何使用Swift从Realm数据库中获取所有类型的对象.是的,是的:

This is really basic but I just can't find how to get all objects of a type from a Realm database using Swift. Yes, yes:

var dogs = try! Realm().objects(Dog)

但是,如果我想事先声明和初始化dogs变量并在以后将对象加载到其中,该怎么办?喜欢:

but what if I want to declare and initialize the dogs variable beforehand and load objects into it later? Like:

var dogs = ???
dogs = realm.objects(Dog)

在这种情况下,可变狗的类型应该是什么?

What should the type of variable dogs be in this case?

推荐答案

Realm.objects(_:) 具有以下签名:

Realm.objects(_:) has the following signature:

public func objects<T: Object>(type: T.Type) -> Results<T>

签名告诉您,当您将函数调用为realm.objects(Dog)时,返回类型将为Results<Dog>.

The signature tells you that when you call the function as realm.objects(Dog), the return type will be Results<Dog>.

如果您想声明变量并稍后在同一函数中对其进行初始化,则可以简单地将声明与初始化分开,如下所示:

If you wish to declare the variable and initialize it later in the same function, you can simply separate the declaration from the initialization, like so:

let dogs: Results<Dog>

// …

dogs = realm.objects(Dog)

如果要声明成员变量并需要在init之后初始化它,则应声明为可选变量并使用var:

If you are declaring a member variable and need to initialize it after init, you should declare as an optional and using var:

var dogs: Results<Dog>?

// …

dogs = realm.objects(Dog)

这篇关于领域结果对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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