gpt4 book ai didi

ios - Swift 中的 Objective-C 协议(protocol)

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:57 25 4
gpt4 key购买 nike

我正在使用 Fusuma cocoal pod 框架。然而,我发现他们有一个 Objective-C 协议(protocol),甚至认为整个项目都是用 Swift 编写的。

@objc public protocol FusumaDelegate: class {

func fusumaImageSelected(image: UIImage)
optional func fusumaDismissedWithImage(image: UIImage)
func fusumaVideoCompleted(withFileURL fileURL: NSURL)
func fusumaCameraRollUnauthorized()

optional func fusumaClosed()
}

我想在协议(protocol)中添加另一个功能。但是,我收到此警告

Method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in objective-C

我正在考虑删除协议(protocol)前面的@objc,但它说我必须删除可选函数。我不介意将它们更改为正常功能,但是,我想了解如果删除 @objc 应该注意什么

我要添加的函数是之前 VC 的另一个委托(delegate)函数。在这种情况下,我有 3 个 VC。第二个是这个,在第三个 VC 被解雇后从它那里获取数据。然后我想添加如下委托(delegate)函数让VC1开始上传数据

extension FusumaViewController: VC3Delegate {
func readyToUploadPost(postUpload: PostUpload) {
delegate_?.readyToUploadPost_Fusuma(postUpload)
}

最佳答案

@HAS 是否说明了此协议(protocol)被赋予@objc 的最可能原因是因为 Swift 不允许您使用可选的协议(protocol)要求方法。这样做的快速方法是:

public protocol FusumaDelegate: class {

func fusumaImageSelected(image: UIImage)
func fusumaVideoCompleted(withFileURL fileURL: NSURL)
func fusumaCameraRollUnauthorized()
}

extension FusumaDelegate {
func fusumaDismissedWithImage(image: UIImage) {/*Default Implementation*/}
func fusumaClosed() {/*Default Implementation*/}
}

当然,我想你会遇到默认实现的问题,但是:

You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension. The Swift Programming Language

这是在 Playground 上创建的,旨在为您提供一个想法,没有任何错误:

public protocol FusumaDelegate: class {
func fusumaImageSelected(image: UIImage)
func fusumaVideoCompleted(withFileURL fileURL: NSURL)
func fusumaCameraRollUnauthorized()
}

extension FusumaDelegate {
func fusumaDismissedWithImage(image: UIImage) {}
func fusumaClosed() {}
}


class Test : UIViewController, FusumaDelegate {
func fusumaImageSelected(image: UIImage) {
//do stuff
}

func fusumaVideoCompleted(withFileURL fileURL: NSURL) {
//do stuff
}

func fusumaCameraRollUnauthorized() {
//do stuff
}

func fusumaDismissedWithImage(image: UIImage) {
//do stuff
self.fusumaClosed()
}
}

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

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