【问题标题】:How to decrease counter in for loop?如何减少for循环中的计数器?
【发布时间】:2016-03-25 03:44:30
【问题描述】:

我正在使用此处的数组随机播放功能: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
}

Swift 抛出这个警告:

C 风格的 for 语句已被弃用,未来将被移除 斯威夫特版本

这里没有关于应该使用什么的建议。有什么想法可以代替它吗?

【问题讨论】:

  • for index in array.indices.reverse() { ... }
  • 这行当 index==0 时应用肯定会崩溃:let j = Int(arc4random_uniform(UInt32(index-1)))

标签: arrays swift for-loop


【解决方案1】:

看看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)  {

}

更多信息:stride 有两个版本:throughtothrough 的区别是 =,而 to 的区别是 ,这取决于您的需要。

【讨论】:

  • 这不起作用,所以我将整个内容发布在 OP 中。
  • 除非你发布你的真实代码并告诉你什么不起作用,或者我不相信。
  • @4thSpace Int(arc4random_uniform(UInt32(index-1))) 总是会崩溃。尽量不要减去 1。你还需要添加一个保护语句以确保在使用交换之前index != j
  • @LeoDabus 你能张贴那会是什么样子吗?守卫必须在函数中使用对吗?我已经在一个函数中,所以我不确定它是如何工作的。
【解决方案2】:
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]

【讨论】:

    【解决方案3】:
    for var index = array.count - 1; index > 0; index -= 1
    

    使用反向范围。形成范围并将其反转:

    for index in (1..<array.count).reverse
    

    但是,正如我在回答 here 中所讨论的,有一个更好的方法;我提供了一个&gt;&gt;&gt; 运算符,所以你可以说

    for index in array.count>>>1
    

    【讨论】:

      【解决方案4】:

      你为什么不试试:

      for var index = array.count - 1; index > 0; index =index-1 ; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2013-10-21
        • 1970-01-01
        相关资源
        最近更新 更多