简体   繁体   中英

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).

/// 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:

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...

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)

This blog explains it: http://useyourloaf.com/blog/swift-optional-protocol-methods/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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