swift - Realm :结果 <T>[索引] 无法正常工作

标签 swift realm

我查询 1000 个联系人的结果,按姓氏排序。然后我创建随机索引并查询对象。但是,我得到的不是随机联系人,而是前 n 个联系人……如果索引不能正常工作,为什么排序结果中的对象可以通过索引来寻址?

if let contacts = ContactsProvider.sharedInstance.loadContactsWithReload(){

    if(contacts.count <= 1){
        return nil;
    }

    if(contacts.count <= 10){
        random10Group.contacts.appendContentsOf(contacts)
    }
    else{
        var randomIndices = [Int]()
        while randomIndices.count < 10{

            let random = Int(arc4random_uniform(UInt32(contacts.count)))
            if(!randomIndices.contains(random)){
                randomIndices.append(random)
                print(random)
            }
        }

        let contactList = List<Contact>()

        for var index = 0; index < randomIndices.count; index++ {
            let contact = contacts[index]
            contactList.append(contact)
            print(contact.fullName())
        }

        random10Group.contacts = contactList

        return random10Group
    }
}

最佳答案

let contactList = List<Contact>()
for var index = 0; index < randomIndices.count; index++ {
    let contact = contacts[index]
    contactList.append(contact)
}

index0randomIndices.count - 1,这就是为什么 你得到第一个联系人。

你可能是说

let contactList = List<Contact>()
for index in randomIndices {
    let contact = contacts[index]
    contactList.append(contact)
}

以便 index 遍历随机数组的元素

注意循环可以简化为

let contactList = randomIndices.map { contacts[$0] }

关于swift - Realm :结果 <T>[索引] 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952906/

相关文章:

java - Realm 是否已经支持原始列表?

ios - 解码动态接收的输出,因为 JWT 在 Swift 3 中不工作。 "The Token is not yet valid (not before claim)"

ios - 如何仅在 CGRect 中使用 Apple Vision 检测条形码?

swift - 具有惰性属性的 Realm 中的复合键

android - 插入或更新的 Realm 顺序

realm - 错误: Realm at path '/var/.../default.realm' already opened on current thread with different schema

ios - Swift 中的警告 : Attempt to present ---- whose view is not in the window hierarchy! 和一个变量未传输

json - 阿拉莫菲尔 得到回应

ios - 如何将 UIview 添加到 SpriteKit 项目?

ios - 只需一次将对象添加到 Realm 列表