clinton clinton - 17 days ago 5
Swift Question

Swift 1.2 - Setting element in array of optional types to nil-- not allowed when passed in?

I've an array of boxes where the types are Box? to allow elements to be set to nil, if there is nothing there. I want the Box to set its spot to nil when it is removed from the scene.

The following causes no complaints from Xcode:

override func removeFromParent() {
var board = [[Box?]](count: 5, repeatedValue: [Box?](count: 9, repeatedValue: nil))
board[i][j] = nil
super.removeFromParent()
}


and neither does making the board variable global and using it that way...

In GameScene.swift:

var board = [[Box?]](count: 5, repeatedValue: [Box?](count: 9, repeatedValue: nil))


in Box.swift:

override func removeFromParent() {
board[i][j] = nil
super.removeFromParent()
}


But trying to do this wont compile (It's no longer overriding because I added a parameter):

func removeFromParent(board: [[Box?]]) {
board[i][j] = nil
super.removeFromParent()
}


Is there any way to make this work? Thanks

Answer

Your problem is that board in the latter case is a let and can not be changed.

Again the Swift error message is misleading here.

If you want it to be an inout parameter then add this like (inout board:... but then you need to pass the parameter by reference with an & in the call like removeFromParent(&myBoxArray).

PS Just tried this in Playground:

var a:[Int] = [1, 2, 3]
func aa(inout a:[Int]) {
  a[1] = 9
}

aa(&a)
a // return [1, 9, 3]
Comments