gpt4 book ai didi

swift - 协议(protocol)扩展中的 "self as?"

转载 作者:行者123 更新时间:2023-11-28 12:03:28 27 4
gpt4 key购买 nike

我正在尝试在协议(protocol)扩展中强制转换“self”。它在真实设备上运行时因 EXC_BAD_ACCESS 错误而崩溃,但在模拟器上运行良好。我应该怎么做才能使这项工作?谢谢

我的整个代码:

protocol SomeProtocol: class {

}

protocol DataSetEditable {
func add(_ data: Data)
}

extension DataSetEditable where Self: SomeClass {
func add(_ data: Data) {
print(data)
if let someProtocol = self as? SomeProtocol {
print(someProtocol)
//do some extra works
}
}
}

class SomeClass: UIView {

}

class MyClass: SomeClass, DataSetEditable, SomeProtocol {
}

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let myClass = MyClass()
myClass.add(Data())
}
}

最佳答案

首先,这可能是一个 Swift 错误,因为如果编译器无法处理它,它应该会提供一个错误。您应该在 bugs.swift.com 打开它.这感觉与SR-544有关.

也就是说,通常来说,要使 ObjC 类型符合 Swift-only 协议(protocol)是非常棘手的。有时有效,有时无效。这是一个相当复杂的一致性,显然它并不总是有效。解决方案是通过添加 @objc 将协议(protocol)公开给 ObjC:

@objc protocol SomeProtocol: class {}

关于swift - 协议(protocol)扩展中的 "self as?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854220/

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