我有一个名为mood的领域对象,我试图将字段活动中的所有值作为[String]列表返回,其中mood = great
My Realm对象如下:
Results<Mood> <0x7fce164851a0> (
[0] Mood {
mood = Great;
comment = test;
activities = Friends;
time = 8:06 PM;
date = 4/10/18;
symptom = down;
},
[1] Mood {
mood = Sad;
comment = ;
activities = Date;
time = 6:22 PM;
date = 4/14/18;
symptom = up;
},
[2] Mood {
mood = Sad;
comment = ;
activities = Date;
time = 7:40 PM;
date = 4/14/18;
symptom = Night;
},
[3] Mood {
mood = Sad;
comment = ;
activities = Date;
time = 7:41 PM;
date = 4/14/18;
symptom = Dry;
},
[4] Mood {
mood = Awful;
comment = this is an example data for the app!;
activities = Date;
time = 2:17 PM;
date = 4/15/18;
symptom = Lost;
}
)
我希望返回一个像
这样的列表[ “向下”] 因为那是心情=伟大等活动
我试过了:
func getGreatMoodActivity() -> [String]{
let greaMoodActivity = Set(realm.objects(Mood.self).filter("mood = 'Great'") as! [String])
return getGreatMoodActivity()
}
但是这个错误会崩溃
无法转换'RealmSwift.Results'类型的值 (0x10f520810)到'NSArray'(0x10ce35008)。
有没有办法解决这个问题?
答案 0 :(得分:0)
filter
操作将继续过滤符合您给定条件的Mood
个对象,因此其返回值将为Results<Mood>
类型,您显然无法将其强制转换为{{ 1}}。
您似乎正在尝试Array<String>
符合您的过滤条件的map
个对象Mood
属性symptom
属性String
。要实现目标,您需要在过滤map
个对象后调用Mood
。
此外,您的返回值完全有缺陷,您希望返回存储在变量greatMoodActivity
中的数组,而不是递归调用您的函数。
func getGreatMoodActivity() -> [String]{
let greatMoodActivity = realm.objects(Mood.self).filter("mood = 'Great'").map({$0.symptom})
return Array(greatMoodActivity)
}