arrays - Index Range Swift 中的新数组

标签 arrays swift

我怎样才能做这样的事情?从数组中取出前 n 个元素:

newNumbers = numbers[0..n]

当前出现以下错误:

error: could not find an overload for 'subscript' that accepts the supplied arguments

编辑:

这是我正在使用的函数。

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]

您的问题可能在于您如何开始声明数组。

编辑:

要修复您的功能,您必须将 Slice 转换为数组:

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]

关于arrays - Index Range Swift 中的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24034398/

相关文章:

php - Mysql 行放入数组 PHP

swift - 如何查询 php 页面并保存它返回给我的值?

android - 具有多项选择的 ExpandableListView 将所选项目保存到数组中

arrays - 创建 3 维 slice (或超过 3 个)

php - 将值添加到 MySQL 结果数组

ios - 在开始新的异步操作之前,快速等待现有的异步操作完成

ios - 如何将 Storyboard UIView 设置为 View 的子类?

ios - 在哪里放置在 View Controller 之间传递数据的函数

在 firebase 中保存时 iOS 快速异常

c(以及 objc、c++ 和 objc++)- char* argv[]