未解析的标识符 - 用于循环逻辑

unresolved identifier - for in loop logic

这是从下到上的排序。在循环时,迭代被替换为数组中的最小数字,并且一直持续到最后。

如您所见,我正在重构以使用 stride。不幸的是 var lowest = firstIndex 给我带来了一些麻烦。

我应该可以用 stride 完成这个功能吧?我相信我应该使用 stride: to 而不是 stride: through。感谢蒂姆的提示。

func selOrganize(myList: Array<Int>) -> Array<Int> { 1

    var extract = myList

    for firstIndex in 0..<extract.count {

        var lowest = firstIndex

        for var secondIndex = firstIndex + 1; secondIndex < extract.count; secondIndex++ {

            if extract[lowest] > extract[secondIndex] {
                lowest = secondIndex
    }
        }

        if firstIndex != lowest {
            swap(&extract[firstIndex], &extract[lowest])
        }   
    }
    return extract 
}

更新语法

func selOrganize(myList: Array<Int>) -> Array<Int> {

var extract = myList

    // var lowest = firstIndex

    // Do I need 'key'? Should I declare 'lowest' as a variable here?
    // If I do use it here I get a "'lowest' is unmutable because it's a let" error
    for (firstIndex, key) in extract.enumerate() {

        // < > stride uses 'to' and  <= >= stride uses through
        for secondIndex in (firstIndex).stride(to: 0, by: +1) {  

            if extract[lowest] > extract[secondIndex] {
                lowest = secondIndex
            }
        }

    if firstIndex != lowest {
        swap(&extract[firstIndex], &extract[lowest])
    }

}

return extract
}

我是这样工作的:

func selOrganize(myList: Array<Int>) -> Array<Int> {

    var extract = myList

    // Accessing indices is simpler than calling enumerate, and
    // the function only needs access to the indices, not the 
    // values of the enumeration:
    for firstIndex in extract.indices {

        // lowest needs to be defined inside this loop if you 
        // are going to initialize it using firstIndex 
        // because firstIndex isn't defined outside the loop.
        var lowest = firstIndex

        // You need to stride from the firstIndex to the end of the
        // array, so the call to stride should look like this:
        for secondIndex in firstIndex.stride(to: extract.count, by: 1) {  

            if extract[lowest] > extract[secondIndex] {
                lowest = secondIndex
            }
        }

        if firstIndex != lowest {
            swap(&extract[firstIndex], &extract[lowest])
        }
    }

    return extract
}
不需要

Stride,您可以使用标准 for i in start..<end 语法

func selOrganize(myList: Array<Int>) -> Array<Int> {

  var extract = myList

  for firstIndex in 0..<extract.count {
  var lowest = firstIndex
    for secondIndex in (firstIndex + 1)..<extract.count {
      if extract[lowest] > extract[secondIndex] {
        lowest = secondIndex
      }
    }

    if firstIndex != lowest {
      swap(&extract[firstIndex], &extract[lowest])
    }
  }
  return extract
}

但实际上你可以在一行中做同样的事情

let sortedList = myList.sort{[=11=] < }