gpt4 book ai didi

ios - ObjC 协议(protocol)在 Swift 中的实现

转载 作者:行者123 更新时间:2023-11-30 13:18:47 25 4
gpt4 key购买 nike

好吧,这是一个大问题。我有一个用 ObjC 编写的库( this )。在那里我们有一个明确的协议(protocol)。当我尝试在 swift 文件中使用它时,我不断得到:

Type "XXX" does not conform to protocol "XXX"

为了简化事情,我创建了一个测试项目 - 它应该创建为 Swift 项目。

然后创建 ObjC 头文件(我称之为 StupidProtocol.h),其中包含以下协议(protocol)(请注意每个名称和值与给定的完全匹配,包括大写/小写):

@protocol MyProtocol <NSObject>

- (NSString *)getAxisLabel:(id)axis Value:(CGFloat)value;

@end

在桥接头中:

#import "StupidProtocol.h"

然后返回 Swift 文件:

class ViewController: UIViewController, MyProtocol
{
func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! {
return ""
}
}

尽管自动完成功能为我完成了 getAxisLabel 函数,但是我们再次遇到了这个错误。

我强烈怀疑问题出在参数“value”及其函数参数“Value”上。

任何帮助将不胜感激。

编辑

请注意 this library从技术上讲不是我的,所以我无法更改它。我需要一种在 Swift 中使用它而不改变它的原始声明的方法。我的例子只是为了简化我的问题。

我尝试了什么

我尝试过以下场景但没有成功:

“参数名称与协议(protocol)所需的参数名称不同”错误

func getAxisLabel(axis: AnyObject!, Value value: CGFloat) -> String! {
return ""
}

“参数名称与协议(protocol)所需的参数名称不同”错误

func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> String! {
return ""
}

“类型不符合协议(protocol)”

func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> NSString! {
return ""
}

解决方案

参见accepted answer

最佳答案

我不知道这是否是一个错误。 Objective-C协议(protocol)方法

- (NSString *)getAxisLabel:(id)axis Value:(CGFloat)value;

(Value: 中带有大写“V”)映射到 Swift 为

func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String!

(value: 中包含小写“v”),但没有

func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! { }
func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> String! { }

被编译器接受以满足协议(protocol)要求。

作为解决方法,您可以使用显式注释该方法Objective-C 选择器名称:

class ViewController: UIViewController, MyProtocol
{
@objc(getAxisLabel:Value:)
func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! {
return ""
}
}

关于ios - ObjC 协议(protocol)在 Swift 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37964323/

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