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

Dmitry picture Dmitry · Oct 3, 2014 · Viewed 13.5k times · Source

Can't connect delegate property of CustomView declared as @IBOutlet toViewController in Interface Builder – simply can't establish a connection.

Here's the code

class CustomView: UIView {
     @IBOutlet var delegate: CustomViewDelegate?
}

@objc protocol CustomViewDelegate {
     ...
}


class ViewController: UIViewController, CustomViewDelegate {
     ...
}

@objc is used because of swift protocol, IBOutlet property cannot have non-object type, don't know why protocol CustomViewDelegate: class {} doesn't work.

Anyone else came across something like that?

Answer

matt picture matt · Oct 3, 2014

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.