5

I have a variable that must be a UIView that also implements the protocol MTMathKeyboard.

I've tried,

var keyboard: (UIView & MTMathKeyboard)
var keyboard: UIView<MTMathKeyboard>

What's the syntax for a non-generic class instance that implements a protocol?

Jacob Parker
  • 297
  • 4
  • 13

4 Answers4

6

In Swift 4 you can use:

let keyboard: UIView & MTMathKeyboard
Jeroen Bakker
  • 2,142
  • 19
  • 22
3

I think you should go this way:

protocol MTMathKeyboard: class {

}

class YourClass<MTMathKeyboard where T:UIView> {
    var keyboard: T!
}
Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
0

You could use protocol composition and extend UIView to meet a placeholder protocol:

protocol UIViewClass {}
extension UIView:UIViewClass {}


var keyboard :  UIViewClass & MTMathKeyboard
Alain T.
  • 40,517
  • 4
  • 31
  • 51
-1
typealias KeyboardView = UIView & MTMathKeyboard

protocol MTMathKeyboard: class {
}

private func updateController(with view: KeyboardView) {
        someView = view
}
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Wasim
  • 921
  • 12
  • 14
  • a good example why sticking to code formatting guidelines is helpful: `someView = keyboard` here an object called `keyboard` does not exists, but it is a type name. – vikingosegundo Mar 12 '19 at 11:50