在 Swift 中实现 Objective c 协议 [英] Implement Objective c protocol in Swift
问题描述
我在一个客观的 c 类中有这个协议:
I have this protocol in a objective c class:
@protocol YTManagerDelegate <NSObject>
@required
- (void)uploadProgressPercentage:(int)percentage;
@end
...
和一个连接到它的 swift 类:
and a swift class connected to it:
class YTShare: UIViewController, YTManagerDelegate{
func uploadProgressPercentage(percentage:Int?){
println(percentage)
}
...
我收到错误:类型 YTShare 不符合 YTShareDelegate 协议,我可能错误地编写了 swift 函数,因此 obj 类找不到它.我怎样才能正确地写出来?
I receive the error: type YTShare does not conform to protocol YTShareDelegate, I have probably write incorrectly the swift function so the obj class don't find it. How I can write it correctly?
推荐答案
委托方法有两个错误
func uploadProgressPercentage(percentage:Int?){
println(percentage)
}
参数不能是可选的,C类型int
映射到Swift作为 CInt
(Int32
的别名):
The parameter must not be an optional, and the C type int
is mapped to Swift
as CInt
(an alias for Int32
):
func uploadProgressPercentage(percentage:CInt){
println(percentage)
}
或者,您可以在 Objective-C 协议中使用 NSInteger
,即在 Swift 中映射到 Int
.这将是一个 32 位或 64 位整数,具体取决于在架构上,而 int
/CInt
总是 32 位.
Alternatively, you could use NSInteger
in the Objective-C protocol, which is
mapped to Int
in Swift. This would be a 32-bit or 64-bit integer, depending
on the architecture, whereas int
/CInt
is always 32-bit.
这篇关于在 Swift 中实现 Objective c 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!