gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:52:01 25 4
gpt4 key购买 nike

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

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

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

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
}

关于swift - 未解析的标识符 - 用于循环逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com