swift2 将shuffle数组方法从Objective C转换为Swift(iOS)

beq87vna  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(162)

我有一个在Objective-C中随机移动一个数组的方法,它工作的很好,但是我在转换它时遇到了一些麻烦。

- (NSArray *)shuffle:(NSArray *)array {

NSMutableArray *newArray = [NSMutableArray arrayWithArray:array];

NSUInteger count = [newArray count];

for (NSUInteger i = 0; i < count; i++) {

    NSInteger remainingCount = count - i;

    NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t)remainingCount);

    [newArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];

}

return [NSArray arrayWithArray:newArray];
}

这是这个方法的Swift版本,在我的“figure out error”注解下面,它抛出了一个错误,说“Ambiguous use of operator '+'”。我只是尝试将“remaining count”转换为arc_4random方法的UInt 32,所以我不确定是怎么回事。有什么想法吗?谢谢!

func shuffle(array: NSArray) -> NSArray {

    let newArray : NSMutableArray = NSMutableArray(array: array)

    let count : NSInteger = newArray.count

    for var i = 0; i < count; ++i {

        var remainingCount = count - i

        //figre out error below

        var exchangeIndex = i + arc4random_uniform(UInt32(remainingCount))

        newArray.exchangeObjectAtIndex(i, withObjectAtIndex: exchangeIndex)
    }

    return NSArray(array: newArray)

}
pxyaymoc

pxyaymoc1#

试试这个

更新的工作代码

func shuffle(array: NSArray) -> NSArray {

        let newArray : NSMutableArray = NSMutableArray(array: array)

        let count : NSInteger = newArray.count

        for var i = 0; i < count; ++i {

            let remainingCount = count - i

            //figre out error below

            let exchangeIndex = i + Int(arc4random_uniform(UInt32(remainingCount)))

            newArray.exchangeObjectAtIndex(i, withObjectAtIndex: exchangeIndex)
        }

        return NSArray(array: newArray)

    }

将arc4random_uniform的结果强制转换为Int

9lowa7mx

9lowa7mx2#

雨燕4.2

现在,从Swift 4.2开始,这个特性已经内置到Swift中了。你可以在原地对一个数组进行洗牌,也可以创建一个新的洗牌数组。

var albums = ["Red", "1989", "Reputation"]

// shuffle in place
albums.shuffle()

// get a shuffled array back
let shuffled = albums.shuffled()
uttx8gqw

uttx8gqw3#

如何随机播放数组

import Foundation // arc4random_uniforn

extension Array {
    func shuffle()->Array {
        var arr = self
        let c = UInt32(arr.count)
        for i in 0..<(c-1) {
            let j = arc4random_uniform(c)
            if i != j {
                swap(&arr[Int(i)], &arr[Int(j)])
            }        
        }
        return arr
    }
}

let arr0 = [1,2,3,4,5,6,7,8,9,0]
for i in 0..<5 {
    print(arr0.shuffle())
}
/*
[6, 4, 0, 1, 8, 9, 3, 5, 2, 7]
[5, 2, 3, 9, 8, 1, 7, 6, 4, 0]
[8, 7, 6, 1, 2, 4, 9, 5, 0, 3]
[2, 4, 7, 6, 5, 9, 8, 1, 0, 3]
[7, 5, 6, 1, 9, 4, 2, 8, 3, 0]

* /

为什么你的代码不能编译,在@z_px的注解中有解释

相关问题