Swift 在实现协议的结构上调用方法

Swift 在实现协议的结构上调用方法,swift,Swift,更新开始 这是因为这个数组来自Objective-C,整个过程中发生了一些错误。需要一些修复,但以下所有答案都是正确的。 更新结束 我有一个协议如下 protocol SomeProtocol { func someFunctionProtocol } 有一个结构将此协议实现为 struct SomeStruct: SomeProtocol { .... } 现在,在运行时,我得到一个参数arg:Any,我确信它将实现SomeProtocol 如何在arg上调用此协议方法。我试

更新开始 这是因为这个数组来自Objective-C,整个过程中发生了一些错误。需要一些修复,但以下所有答案都是正确的。 更新结束

我有一个协议如下

protocol SomeProtocol
{
    func someFunctionProtocol
}
有一个结构将此协议实现为

struct SomeStruct: SomeProtocol
{
   ....
}
现在,在运行时,我得到一个参数
arg:Any
,我确信它将实现
SomeProtocol

如何在
arg
上调用此协议方法。我试过了
让ob=arg为!HanselProviderProtocol
,但这会导致运行时错误
无法将类型为“\u SwiftValue”(0x111952720)的值强制转换为“SomeProtocol”(0x111957158)

下面的图片显示它不工作

=====

类型将
任何
类型强制转换为
结构
类型,而不是
协议

guard let ob = arg as? SomeStruct else { 
 print("invalid type")
 return 
}

ob.someFunctionProtocol()
编辑

或者只需使用
is
关键字进行检查

 let foo: Any = SomeStruct()

 if foo is SomeProtocol {
   // you can safely use force unwrapping here, because the condition above returned true
   (foo as! SomeProtocol).someFunctionProtocol()
 }
如果要使用SwiftLint,可以使用以下命令禁用强制强制施放警告或错误:

// swiftlint:disable:this force_cast

如果可能有更多不同的结构实现协议,请使用:

protocol SomeProtocol {
    func a()
}

struct SomeStruct: SomeProtocol {
    func a() {
        print("a called from SomeStruct")
    }
}

let x = SomeStruct() as Any // Just as an example

if let x = x as? SomeProtocol {
    x.a()
}

如果您的值为
Any
类型,则可以测试一致性并执行如下操作:

(arg as? SomeProtocol)?.someFunction() 
或者,如果您希望其范围更广:

guard let conformer = arg as? SomeProtocol else { return }
conformer.someFunction()

在Swift3中,您可以将类型为
Any
的参数强制转换为协议:

protocol SomeProtocol {
    func someFunctionProtocol()
}

struct SomeStruct: SomeProtocol {
    func someFunctionProtocol() {
        print("Yep")
    }
}

func test(arg: Any) {
    if let castee = arg as? SomeProtocol {
        castee.someFunctionProtocol()
    }
}

test(arg: SomeStruct())
印刷品:

Yep


离题:不要告诉我们
在Swift代码中。使用
guard
代替。谢谢您的建议。虽然我会处理它,但它也会解决运行时崩溃并调用由
SomeStruct
实现的方法吗。它可能会解决运行时崩溃,但最终不会调用该方法。@prabodhprakash提供更多示例我不确定。请尝试
guard let ob=arg as?一些协议
。但我不确定您是否可以强制转换为协议类型。尝试强制转换为结构类型。如果您提供一个,这将非常有用。我无法将其强制转换为
SomeStruct
,因为实现协议的
struct
可能不止此
arg
,而不仅仅是检查
is
关键字。更新了我的答案。不强制转换的问题是你不能调用协议函数。''arg.someFunctionOfProtocol()`将不会编译,即使您知道它
是SomeProtocol
。那么,只需强制将变量强制转换为协议即可。更新了我的答案。例如,当您使用swiftlint时,强制强制转换可能会破坏您的构建。
(arg as?SomeProtocol)?
失败-我希望它通过-因为它确实实现了
SomeProtocol
,如果失败,则不会,它实际上没有实现
SomeProtocol
。听起来您对参数中显示的内容有误解,问题实际上在代码的其他地方。如果您有时间,我们可以使用Skype,我可以向您展示代码。我已经编辑了问题,添加了显示故障的图像。我无法将其转换为
SomeStruct
,因为可能有更多的
struct
实现了协议,并且输入了
arg
,我没有将其转换为struct。对我来说,独立运行很好,但我的代码中却出现了故障!-让我看看我是否犯了什么错误。