gpt4 book ai didi

swift - 检查类是否符合协议(protocol)

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

我正在尝试快速为我们的应用程序制作一个简单的依赖注入(inject)系统,现在已经 2 天了。我对任何解决方案都很灵活,但我想要一些东西,所以我可以说“给我一个符合此协议(protocol)的实例”,并且返回的实际类型可以是任何类型,只要它符合上述协议(protocol)即可。我已经尝试了很多东西,包括泛型,但设法弄清楚它不能(?)真正起作用,所以现在我只剩下最基本的东西,像这样:

protocol AProtocol {

}

class AClass: AProtocol {

}

class MyDiThing {
public static func objectConformingTo(aProtocol: Any) -> Any? {
// And here I want to do something like
if AClass is aProtocol {
return AClass()
}
return nil
}
}

// The calling code ..
let aObject = MyDIThing.objectConformingTo(AProtocol)

它并不漂亮,我知道,但现在我对性能/糟糕的代码并不那么挑剔,只要它解决了解耦问题(最好可以包含在 MyDIThing 类中)。如果这在 swift 中是不可能的,我愿意接受其他解决方案。我在 objective-c 中使用了类似的解决方案并取得了很好的成功,只是有一个字典,键是 NSStringFromProtocol,值是类,用入站协议(protocol)为字典下标并实例化类。 super 简单。很快就感觉不可能了!

最佳答案

nhgrif 给出的注释是 Swift 2 的正确答案。您应该使用可选绑定(bind):

if let aObjectWithAProtocol = aObject as? AProtocol {
// object conforms to protocol
someObject.someFunction(aObjectWithAProtocol)
} else {
// object does not conform to protocol
}

这个 if let something = obj as? type 语句称为 optional binding 并检查对象是否可以类型转换为给定的类型/类/协议(protocol)/....

如果是这样,您可以使用可选的 (as?) 或强制展开 (as!) 对象。

关于swift - 检查类是否符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660979/

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