SLN
SLN

Reputation: 5092

Xcode8 Beta EXC_BAD_ACCESS Error appears when creates weak references

The following code is copied from the Weak References section of the Official document

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john //Error!

It basically described the strong and weak reference relationship between a person type instance and an Apartment type instance (Please see the figure bellow)

enter image description here

However, when I run the code, I got an error.

Question: How can I fix it?

enter image description here

In reply of Mr. Alessandro Orrù, (I copy and pasted it again and it still gives me error)

enter image description here

Upvotes: 3

Views: 580

Answers (1)

DavidA
DavidA

Reputation: 3172

This now works correctly - the bug has been fixed in XCode 8 GM Seed.

Original Answer:

It's a bug in playgrounds in or XCode8 beta 3. I copied your code, tried the Apple example, and tried reducing it to the minimum:

class A { var b:B? }

class B { weak var a:A? }

let b = B()
let a = A()

a.b=b
b.a=a

All work as expected with XCode 7.3.1 and Swift 2.2. All fail with XCode 8 beta 3 and Swift 3. The error is:

error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).

It's in playgrounds only - it's fine in an app. (I tried a Mac OS command line program)

Upvotes: 1

Related Questions