Subscript error in Swift Array
我正在用swift实现合并排序算法。下面是我做的功能
1 2 3 4 5 6 7 8 9 10 11 | func mergeSort(unsortedArray: [Int]) -> [Int] { guard unsortedArray.count > 1 else { return unsortedArray } let middleIndex = unsortedArray.count / 2 let leftArray = mergeSort(unsortedArray: unsortedArray[0..<middleIndex]) let rightArray = mergeSort(unsortedArray: unsortedArray[middleIndex..<unsortedArray.count]) return merge(leftPile: leftArray, rightPile: rightArray) } |
在
1 2 3 4 5 6 | Playground execution failed: error: MergeSort.xcplaygroundpage:4:59: error: cannot subscript a value of type '[Int]' with an index of type 'CountableRange<Int>' let leftArray = mergeSort(unsortedArray: unsortedArray[0..<middleIndex]) ^ MergeSort.xcplaygroundpage:4:59: note: overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>), (Range<Self.Index>), (ClosedRange<Self.Index>), (CountableClosedRange<Self.Index>) let leftArray = mergeSort(unsortedArray: unsortedArray[0..<middleIndex]) |
号
这里有人能解释一下这个问题吗?答案键说我应该按照以下方式实现,但我不确定为什么要将数组包装在数组中。
1 2 3 | let leftArray = mergeSort(unsortedArray: Array(unsortedArray[0..<middleIndex])) let rightArray = mergeSort(unsortedArray: Array(unsortedArray[middleIndex..<unsortedArray.count])) |
您没有在数组中包装数组。您将非数组的内容强制到数组中。