Interface Builder, @IBOutlet and protocols for delegate and dataSource in Swift Interface Builder, @IBOutlet and protocols for delegate and dataSource in Swift swift swift

Interface Builder, @IBOutlet and protocols for delegate and dataSource in Swift


From the Xcode release notes:

Interface Builder does not support connecting to an outlet in a Swift file when the outlet’s type is a protocol.

Workaround: Declare the outlet's type as AnyObject or NSObject, connect objects to the outlet using Interface Builder, then change the outlet's type back to the protocol.

EDIT: Xcode 9 beta 3 release notes say that this workaround should no longer be necessary.


Adam Waite provides a nice workaround. I however prefer the following solution as it emphasizes the workaround and the extra property can also easily be removed once Xcode gets fixed.

class CustomView: UIView {    @IBOutlet    public var delegate: CustomViewDelegate?    /// Workaround for Xcode bug that prevents you from connecting the delegate in the storyboard.    /// Remove this extra property once Xcode gets fixed.    @IBOutlet    public var ibDelegate: AnyObject? {        get { return delegate }        set { delegate = newValue as? CustomViewDelegate }    }    func someMethod() {        // Here we always refer to `delegate`, not `ibDelegate`        delegate?.onSomethingHappened()    }}@objc protocol CustomViewDelegate {    ...}

Hey, is this bug already one and a half years old?


An elegant workaround:

#if TARGET_INTERFACE_BUILDER@IBOutlet open weak var delegate: AnyObject?#elseopen weak var delegate: CustomViewDelegate?#endif

See:https://github.com/WenchaoD/FSPagerView/blob/master/Sources/FSPagerView.swift#L88