【问题标题】:Cannot assign value of type Int to element of Int array in Swift 2.1无法将 Int 类型的值分配给 Swift 2.1 中的 Int 数组的元素
【发布时间】:2016-04-28 11:24:39
【问题描述】:

在我的应用程序中,我有 ViewController 类。在这个类中,我有实例变量队列,它是 Int 类型的数组。在其中一个函数中,我需要将一个 Int 类型的值分配给该数组的其中一个元素。该应用程序在没有任何错误和警告的情况下构建,运行完美,直到它仅在我有此分配的那个地方抛出 EXC_BREAKPOINT(在名为 findPath 的函数中)。代码如下:

class ViewController: UIViewController {

     var queue = [Int]()

     func findPath(source: Int, target: Int) {

          queue[0] = 0 // here comes the EXC_BREAKPOINT

     }

}

没关系,我要给这个元素赋什么值:0、-1、1000等等,总会抛出异常。

我正在使用最新版本的 Xcode 7.2 7C68、最新的 iOS 9.2 SDK。我正在部署到 8.1 并在装有 iOS 8.1.2 的 iPhone 5S 上测试该应用程序。

【问题讨论】:

  • 你试过self.queue.add(0)吗?
  • 你不能需要附加queue.append(0)
  • 您正在尝试更改不存在的元素的值

标签: ios arrays swift int


【解决方案1】:
var queue = [Int]()

上面的代码创建了一个整数数组的新实例,但是这个实例还没有任何值。在您当前的代码中,您尝试访问 queue 数组中的 first 值...由于给定索引处没有值,因此您会收到错误消息。

如果您尝试向新数组添加值,您可以使用 append:

var queue = [Int]()

func findPath(source: Int, target: Int) {
    // do this to populate a new array
    queue.append(1)   
}

如果您希望为已有值的数组设置新值,您可以这样做:

var queue = [0, 1, 2]

func findPath(source: Int, target: Int) { 
    // do this to change values in an existing array
    queue[0] = 0 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多