简体   繁体   English

具有可选功能实现的Swift @objc协议会导致生成错误

[英]Swift @objc protocol with optional function implemention causes build error

I have the following protocol (which I'm using as a IBOutlet reference to the storyboard, so it must be with @objc). 我有以下协议(我将其用作对情节提要的IBOutlet引用,因此必须与@objc一起使用)。

/// This protocol implemented by views that contain a **main** 
    collection view.
@objc protocol CollectionInViewMethods {

      /// Notify the view that scrolling occurred.
      @objc optional func setSortingMenuFrame(newFrame: CGRect)
}

When I try to access the optional function using the swift syntax as follows: 当我尝试使用swift语法访问可选函数时,如下所示:

self.cineamsView.setSortingMenuFrame?(newFrame: CGRect())

Which results with 哪个结果

Command failed due to signal: Segmentation fault: 11

While force unwrap build successfully (! instead of ?) 在强制展开构建成功的同时(!而不是?)

Is there any reason for that to happen? 有什么理由要发生吗? I saw that objective C does support optional functions in protocols, it seems to me like an Xcode bug... 我看到目标C确实支持协议中的可选功能,在我看来,这就像一个Xcode错误...

I think you need to unwrap the function first see if it's not nil before calling it (only if you bridge it with a objective-c protocol) 我认为您需要先解开该函数,然后再调用它(如果仅使用Objective-C协议将其桥接),看它是否不是nil

This blog explains it: http://useyourloaf.com/blog/swift-optional-protocol-methods/ 该博客对此进行了解释: http : //useyourloaf.com/blog/swift-optional-protocol-methods/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM