来自Index Range Swift的新数组 [英] New Array from Index Range Swift
本文介绍了来自Index Range Swift的新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做?从数组中获取前n个元素:
How can I do something like this? Take the first n elements from an array:
newNumbers = numbers[0..n]
当前出现以下错误:
error: could not find an overload for 'subscript' that accepts the supplied arguments
这是我正在使用的功能.
Here is the function that I'm working in.
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = numbers[0...position]
return newNumbers
}
推荐答案
这对我有用:
var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]
您的问题可能在于您如何声明数组的开始.
Your issue could be with how you're declaring your array to begin with.
要修复功能,必须将Slice
强制转换为数组:
To fix your function, you have to cast your Slice
to an array:
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = Array(numbers[0..<position])
return newNumbers
}
// test
aFunction([1, 2, 3], 2) // returns [1, 2]
这篇关于来自Index Range Swift的新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文