gpt4 book ai didi

swift - 如何转换为类中的协议(protocol)类型?

转载 作者:行者123 更新时间:2023-11-28 07:34:22 25 4
gpt4 key购买 nike

这是我的代码:

protocol ProtocolA {
static var myProperty: Int { get }
}

protocol ProtocolB {}

extension ProtocolB {
func letsDoSomething() {
(Self.self as! ProtocolA.Type).myProperty // Works
}
}

class MyClass {
func castSelfToProtocolAType() {
(Self.self as! ProtocolA.Type).myProperty // Doesn't work
(Self as! ProtocolA.Type).myProperty // Doesn't work also
}
}

如何将 MyClass 中的 self 转换为动态类型(如在协议(protocol)扩展中)ProtocolA.Type

最佳答案

根据您的问题,您正在尝试将您的类实例转换为协议(protocol)类型实例,这是不可能的,因为您的类不符合该协议(protocol)。

The direct casting from class/struct instance to protocol type instance is not possible, you can only convert to protocol type by accepting that class/struct as a method parameter or by assigning to the other property which protocol type, this is known as implicit type casting.

请阅读本文以了解有关协议(protocol)和类类型的更多信息

  1. https://medium.com/swift-india/protocol-the-power-of-swift-5dfe9bc41a99
  2. https://medium.com/swift-india/protocol-the-power-of-swift-950c85bb69b1
  3. https://medium.com/swift-india/protocol-the-power-of-swift-45e97f6531f9
  4. https://medium.com/@hitendrahckr/protocol-the-power-of-swift-6906cdedd867
  5. https://medium.com/swift-india/protocol-the-power-of-swift-1e5b86bfd1dc

关于swift - 如何转换为类中的协议(protocol)类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638305/

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