EXC_BAD_ACCESS when trying to call a function on a prototype

It was an interesting quick problem that I ran into. Consider the following class and protocol:

class Person {

}

protocol Parent where Self: Person {
    func speak()
}

class GrandMotherPerson: Person, Parent {
    func speak() {
        print("I am a Grandmother Person")
    }
}

class GrandFatherPerson: Person, Parent {
    func speak() {
        print("I am a Grandfather Person")
    }
}

let gmp = GrandMotherPerson()
let gfp = GrandFatherPerson()

Now when you call

gmp.speak() // Output: I am a Grandmother Person
gfp.speak() // Output: I am a Grandfather Person

But if you go to parent

(gmp as Parent).speak() // EXC_BAD_ACCESS when it should say "I am a Grandmother Person"

but if I print(String(describing: gmp))say it__lldb_expr_226.GrandMotherPerson

Why can't I make a quick call speakin class? If you remove where Self: Personfrom the protocol, then it will work as expected.

+4
source share
1 answer

I am sure this is the same deep question that was discussed in detail at https://bugs.swift.org/browse/SR-55 . Think that this compiles and runs just fine:

class Person : NSObject {}
@objc protocol Parent where Self: Person {
    func speak()
}
class GrandMotherPerson: Person, Parent {
    func speak() {
        print("I am a Grandmother Person")
    }
}
let gmp = GrandMotherPerson()
let parent = gmp as Parent
parent.speak() // I am a Grandmother Person

But now delete @objc, and we will get the same problem as yours:

class Person : NSObject {}
protocol Parent where Self: Person {
    func speak()
}
class GrandMotherPerson: Person, Parent {
    func speak() {
        print("I am a Grandmother Person")
    }
}
let gmp = GrandMotherPerson()
let parent = gmp as Parent
parent.speak() // EXC_BAD_ACCESS

, , Swift , . @objc, .

. , , , (gmp as Parent).speak() - , , .

+3

Source: https://habr.com/ru/post/1692592/


All Articles