App doesn't crash when using code in book

On pg. 164, we are instructed to use the following code in the second for loop

array.remove(at:0)

however, this does not cause the app to crash because the remove(at:) method removes the object matching the argument. What is needed, and what is in the solution code is

array.removeObject(at:0) 

which will properly cause the crash.
I’m curious why the method is called remove(at:) when it doesn’t remove from a location.

1 Like

Indeed i have corroborated this and the app does not crash, i don’t why either.

1 Like

I encountered this problem too, thanks your reply.

1 Like

Here are the docs for NSMutableArray remove(_ anObject: Any):

func remove(_ anObject: Any)
Removes all occurrences in the array of a given object.
This method determines a match by comparing anObject to the objects in the receiver using the isEqual: method. If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

The authors intended to remove more objects than exist in the array, but this method removes objects by comparing each element in the array to the object passed as an argument.

As mwbeatty figured out, NSMutableArray removeObject(at index: Int) is the correct method:

func removeObject(at index: Int)
Parameters
index
The index from which to remove the object in the array. The value must not exceed the bounds of the array.
Important
Raises an exception NSRangeException if index is beyond the end of the array.

What’s strange is there’s no error with regard to the “at:” label, which is incorrect. After digging around in Swift docs for a bit and experimenting in a playground I can only guess that it has something to do with how Swift calls Objective-C code (i.e. NSMutableArray.) I wonder if labels are ignored for Obj-C methods with only one parameter.

1 Like

Thank you! I was wrapping my head around this one :slight_smile:

Thank you! I had the same problem!

array.remove(at: 0)

is the corresponding call for a swift array. When the button is pressed, this will give an error that “Index out of range”.

var array = Array()

    for i in 0..<10 {
        array.insert(i, at: i)
    }
    // Go one step too far for emptying the array (notice the range change):
    for _ in 0...10 {
        array.remove(at: 0)
    }

I’m in a similar bind .remove(at:) gives me a “Extraneous argument label ‘at:’ in call” compiler error.

What worked for me: .removeObject(at: 0) (Xcode 9.3.1, Swift 4)

3 Likes