是否有任何约定可以为我在 Swift 中使用的对象生成过滤文本?
class Account {
var active : Bool!
...
}
示例:我在 Swift 中有帐户类,在环回中有帐户模型,我想获得字段为“active = true”的帐户
我需要生成的过滤器是 = {"where": {"active": true}}
我需要手动输入这些类型的查询。我敢肯定有人想到了一种方法,我只需要关键字。
PS:我从 Realm 和 ObjectMapper 扩展了我的类。
最佳答案
更新的答案
如果我理解您在我原来的回答下的评论,您需要生成一个 JSON String,格式为 {"where": {"active": true}}
其中 true
实际上是您的 Account
实例的 bool 值。然后,此 JSON 字符串将用作 MongoDB 的查询/过滤器。
为此,我建议您向 Account
类添加一个计算属性。此属性将使用 NSJSONSerialization
从 bool 创建 JSON data,并使用 String()
创建 JSON String 来自这个数据。
例子:
class Account {
var active : Bool!
var boolQuery: String? {
let dict = ["where": ["active": active]]
if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
query = String(data: json, encoding: NSUTF8StringEncoding) {
return query
}
return nil
}
}
用法:
let acc = Account()
acc.active = true
if let query = acc.boolQuery {
print(query)
}
打印:
{"where":{"active":true}}
let acc = Account()
acc.active = false
if let query = acc.boolQuery {
print(query)
}
打印:
{"where":{"active":false}}
我不确定我是否在您的设置中得到了“谁做什么”(哪个类负责什么),但在我看来,这就是您需要的代码类型。
当然也可以是免费函数:
func boolQuery(account: Account) -> String? {
let dict = ["where": ["active": account.active]]
if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
query = String(data: json, encoding: NSUTF8StringEncoding) {
return query
}
return nil
}
等等
上一个回答
你的问题有点不清楚,我不确定你所说的“我需要手动输入这些类型的查询”是什么意思......但我想,无论如何,你有一组 Account
实例。
然后很容易过滤这个数组,只获取active
为true
的实例:
let result = arrayOfAccounts.filter { $0.active }
此处 result
是一个数组,仅包含 active
为 true 的帐户。
关于json - 如何为 JSON 生成过滤字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533213/