我在这里使用数组shuffle函数:http://iosdevelopertips.com/swift-code/swift-shuffle-array-type.html。
在这一行:
for var index = array.count - 1; index > 0; index -= 1
在下面的代码中
func shuffleArray<T>( arrayparam: Array<T>) -> Array<T>
{
var array = arrayparam
for var index = array.count - 1; index > 0; index -= 1
{
// Random int from 0 to index-1
let j = Int(arc4random_uniform(UInt32(index-1)))
// Swap two array elements
// Notice '&' required as swap uses 'inout' parameters
swap(&array[index], &array[j])
}
return array
}
斯威夫特抛出这个警告:
C-style for语句已弃用,将来会被删除 版本的Swift
这里没有任何关于应该使用的建议。任何想法应该取代它吗?
答案 0 :(得分:2)
看看http://bjmiller.me/post/137624096422/on-c-style-for-loops-removed-from-swift-3
仅减少1:
for i in (0...n).reverse() {
}
或
减少更多步骤:
for i in someNum.stride(through: 0, by: -2) {
}
更多信息:步幅有两个版本:through
和to
。对于through
,差值是&lt; =和&gt; =,而&lt; =&gt; =和&gt;对于to
,取决于您的需要。
答案 1 :(得分:1)
func shuffle<T>(array: Array<T>) -> Array<T> {
var result = array
for index in array.indices.reverse() {
// generate random swapIndex and add a where clause
// to make sure it is not equal to index before swaping
guard
case let swapIndex = Int(arc4random_uniform(UInt32(array.count - index))) + index
where index != swapIndex
else { continue }
swap(&result[index], &result[swapIndex])
}
return result
}
var arrInt = Array(1...100)
shuffle(arrInt) // [28, 19, 25, 53, 35, 60, 14, 62, 34, 15, 81, 50, 59, 40, 89, 30, 2, 54, 27, 9, 82, 21, 11, 67, 84, 75, 44, 97, 66, 83, 36, 20, 26, 1, 76, 77, 8, 13, 72, 65, 64, 80, 88, 29, 98, 37, 33, 70, 52, 93, 100, 31, 4, 95, 45, 49, 61, 71, 24, 16, 12, 99, 94, 86, 46, 69, 63, 22, 48, 58, 51, 18, 43, 87, 41, 6, 92, 10, 38, 23, 68, 85, 42, 32, 55, 78, 56, 79, 3, 47, 39, 57, 90, 17, 5, 73, 7, 91, 74, 96]
答案 2 :(得分:0)
for var index = array.count - 1; index > 0; index -= 1
使用反向范围。形成范围并反转它:
for index in (1..<array.count).reverse
然而,正如我的回答here中所讨论的那样,有一种更好的方式;我提供>>>
运算符,您可以说
for index in array.count>>>1
答案 3 :(得分:-2)
你为什么不试试:
for var index = array.count - 1; index > 0; index =index-1 ;