Swift: EXC_BAD_ACCESS calling array.insert()

Originator:craig
Number:rdar://21174999 Date Originated:31-May-2015
Status:Closed Resolved:10-Jun-2015
Product:OS X SDK Product Version:10.10.3
Classification:High Reproducible:Always
 
Summary:
Calling array.insert() with a struct instance containing a reference to a protocol crashes with EXC_BAD_ACCESS

Steps to Reproduce:
Run the following code:

public protocol Pet       {}
public class    Dog : Pet {}

public struct Person {
    public let pet : Pet
    public init(_ pet: Pet) { self.pet = pet }
}

let rex = Dog()         // rex is a dog
let john = Person(rex)  // john has a dog

// lets start simple and see if using Dog works
var pets = [ rex, rex ]
pets.append(rex)                // works
pets.insert(rex, atIndex: 0)    // works

// now do the same thing for a Person...
var people = [ john, john ]
people.append(john)             // works
people.insert(john, atIndex: 0) // EXC_BAD_ACCESS

println("done")

As I've indicated above, trying to insert an instance of Person into an array fails, whereas inserting an instance of Dog works just fine.  Where it gets really weird is that if I change my Person struct to have references to the Dog struct instead of Pet protocol everything works as expected.


Expected Results:
The call to people.insert() should insert the john object into the array.

Actual Results:
Crashes with a EXC_BAD_ACCESS.  

Side note, if you cut'n'paste the above code into a Playground, you'll notice that it just silently stops running (and "done" doesn't get printed). However, if you run it as a test case, then it bombs with EXC_BAD_ACCESS.

Version:
Version 6.3.2 (6D2105)

Notes:
Another user on  the devforums has identified some more info:

struct Foo {
    let v: Printable = 1234
}
var foos = [Foo(), Foo()]
foos.append(Foo())
foos.insert(Foo(), atIndex: 0) // Runtime error: Thread 1: EXC_BAD_ACCESS (code=1, address = 0xfffffffffffffffc)
println(foos.count)

It will only crash with that exact setup before foos.insert.

For example, it won't crash if the line foos.append(Foo()) is removed, or if the number of initial Foo()'s in the array is changed to something else than two.

Configuration:
MacBook Pro (Retina, Mid 2012)
Yosemite 10.10.3 (14D136)
Xcode 6.3.2 (6D2105)

Comments

Can confirm that this is fixed in Xcode 7.0 beta (7A120f)


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!