2

In Objective C we can declare a delegate this way

@property (nonatomic, weak) id<SomeProtocol> delegate

and in swift

weak var delegate : SomeProtocol?

but in Objective C we can force the delegate to be of a certain class:

@property (nonatomic, weak) UIViewController<SomeProtocol> delegate

how i do this in swift?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Pedro
  • 487
  • 1
  • 5
  • 18
  • Duplicate of http://stackoverflow.com/questions/36906088/what-is-equivalent-of-idtype-in-swift or http://stackoverflow.com/questions/25214484/how-do-i-declare-a-variable-that-has-a-type-and-implements-a-protocol ? – Martin R Sep 15 '16 at 14:45

1 Answers1

0

Swift requires you to know the size of the type at compile time, so you would need to make your class generic to your delegate type:

protocol SomeProtocol: class {}
class SomeClass<T: UIViewController> where T: SomeProtocol {
    weak var delegate : T?
}

There's another option, if you really don't care about it being constrained to a certain type, but to a certain interface, you could describe the UIViewController via another protocol that exposes the methods you need of it.

protocol UIViewControllerProtocol: class,
    NSObjectProtocol,
    UIResponderStandardEditActions,
    NSCoding,
    UIAppearanceContainer,
    UITraitEnvironment,
    UIContentContainer,
    UIFocusEnvironment {
    var view: UIView! { get set }
    func loadView()
    func loadViewIfNeeded()
    var viewIfLoaded: UIView? { get }
}
extension UIViewController: UIViewControllerProtocol {}

protocol SomeProtocol: class {}
class SomeClass {
    weak var delegate : SomeProtocol & UIViewControllerProtocol?
}

This will let you use many of the methods and properties in a UIViewController, but it doesn't really constraint your delegate to be a UIViewController because any other object could implement this protocol and be used instead.

PS: this is Swift 3.0

NiñoScript
  • 4,523
  • 2
  • 27
  • 33