我如何在 swift 中随机播放 RLMResults?
How can i shuffle RLMResults in swift?
知道如何为 RLMResults
随机洗牌吗?无论如何我都找不到通过 RLMSortDescriptor
.
来做到这一点
我尝试编写自己的交换算法,但出现错误(无法分配给此表达式的结果*)。
func simpleRandomSwap(rlmobjects:RLMResults!) -> RLMResults! {
if (rlmobjects != nil && rlmobjects.count > 0) {
let indexcount = Int(rlmobjects.count)
for (var i=0 ; i<indexcount; i++) {
let randomUInt:UInt = UInt(arc4random_uniform(UInt32(indexcount)))
let myuint = UInt(i)
// simple swap
var temp = rlmobjects.objectAtIndex(myuint)
rlmobjects.objectAtIndex(randomUInt) = rlmobjects.objectAtIndex(myuint)
rlmobjects.objectAtIndex(myuint) = temp
} // end for loop
}
return rlmobjects
}
首先要注意一点:RLMResults
没有明确的顺序,除非它们通过 RLMSortDescriptor
排序。
相反,要随机排序,您有两种选择:
向您的对象模式添加一个整数 属性 并为所有对象分配随机值。然后,您可以使用 RLMSortDescriptor
和 RLMResults
对对象进行排序。
如上面评论所述,将RLMObjects
复制到一个数组中并对其进行随机排序。
这是 RLMObject
的一个扩展,可以做到这一点:
extension RLMResults {
public func toShuffledArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for result in self {
if let result = result as? T {
array.append(result)
}
}
let count = array.count
if count > 1 {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + Int(i)
swap(&array[i], &array[j])
}
}
return array
}
}
你可以这样称呼它:
let shuffled = results.toShuffledArray(TestObject.self)
Swift 5:
您可以使用默认方法:
let shuffled = results.shuffled()
知道如何为 RLMResults
随机洗牌吗?无论如何我都找不到通过 RLMSortDescriptor
.
我尝试编写自己的交换算法,但出现错误(无法分配给此表达式的结果*)。
func simpleRandomSwap(rlmobjects:RLMResults!) -> RLMResults! {
if (rlmobjects != nil && rlmobjects.count > 0) {
let indexcount = Int(rlmobjects.count)
for (var i=0 ; i<indexcount; i++) {
let randomUInt:UInt = UInt(arc4random_uniform(UInt32(indexcount)))
let myuint = UInt(i)
// simple swap
var temp = rlmobjects.objectAtIndex(myuint)
rlmobjects.objectAtIndex(randomUInt) = rlmobjects.objectAtIndex(myuint)
rlmobjects.objectAtIndex(myuint) = temp
} // end for loop
}
return rlmobjects
}
首先要注意一点:RLMResults
没有明确的顺序,除非它们通过 RLMSortDescriptor
排序。
相反,要随机排序,您有两种选择:
向您的对象模式添加一个整数 属性 并为所有对象分配随机值。然后,您可以使用
RLMSortDescriptor
和RLMResults
对对象进行排序。如上面评论所述,将
RLMObjects
复制到一个数组中并对其进行随机排序。
这是 RLMObject
的一个扩展,可以做到这一点:
extension RLMResults {
public func toShuffledArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for result in self {
if let result = result as? T {
array.append(result)
}
}
let count = array.count
if count > 1 {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + Int(i)
swap(&array[i], &array[j])
}
}
return array
}
}
你可以这样称呼它:
let shuffled = results.toShuffledArray(TestObject.self)
Swift 5:
您可以使用默认方法:
let shuffled = results.shuffled()