gpt4 book ai didi

swift - EXC_BAD_ACCESS 尝试在原型(prototype)上调用函数时

转载 作者:搜寻专家 更新时间:2023-10-30 23:00:53 25 4
gpt4 key购买 nike

这是我遇到的一个有趣的快速问题。考虑以下类和协议(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()

现在当你打电话

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

但是如果你投给父级

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

但是如果我print(String(describing: gmp))它说它是一个__lldb_expr_226.GrandMotherPerson

为什么不能在类里面快速调用speak?如果您从协议(protocol)中删除 where Self: Person,那么它会按预期工作。

最佳答案

我很确定这与在 https://bugs.swift.org/browse/SR-55 上详细讨论过的问题相同.考虑到这编译和运行得很好:

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

但是现在删除 @objc,我们会遇到与您遇到的相同问题:

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() 似乎还有一个问题——显然我们需要一个对存在的实际变量引用,而不是一个隐式的临时变量。

关于swift - EXC_BAD_ACCESS 尝试在原型(prototype)上调用函数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com