美文网首页
iOS数组乱序

iOS数组乱序

作者: 倒着游的鱼 | 来源:发表于2019-04-08 20:09 被阅读0次
/*
 *  @brief 将数组随机打乱
 */
- (NSArray *)mub_randomArray {
    // 转为可变数组
    NSMutableArray * tmp = self.mutableCopy;
    // 获取数组长度
    NSInteger count = tmp.count;
    // 开始循环
    while (count > 0) {
        // 获取随机角标
        NSInteger index = arc4random_uniform((int)(count - 1));
        // 获取角标对应的值
        id value = tmp[index];
        // 交换数组元素位置
        tmp[index] = tmp[count - 1];
        tmp[count - 1] = value;
        count--;
    }
    // 返回打乱顺序之后的数组
    return tmp.copy;
}

相关文章

网友评论

      本文标题:iOS数组乱序

      本文链接:https://www.haomeiwen.com/subject/vcxmiqtx.html