SirRupertIII
SirRupertIII

Reputation: 12595

Can I force protocol conformation in Swift?

I'd like to do this:

UIView <UITextFieldDelegate>*

in swift.

Making an object that subclasses UIView also conform to the UITextFieldDelegate protocol.

Upvotes: 1

Views: 606

Answers (2)

rintaro
rintaro

Reputation: 51911

You can express (id <UITextFieldDelegate, UIScrollViewDelegate>) using Protocol Composition
but not (UIView<UITextFieldDelegate> *). except for class definition.

// Obj-C
- (void)methodName:(id <UITextFieldDelegate, UIScrollViewDelegate>)arg { ... }

// Swift
func methodName(arg:protocol<UITextFieldDelegate, UIScrollViewDelegate>!) { ... }

Actually, an Obj-C method declared as - (void)methodName((UIView<UITextFieldDelegate> *))arg;, when it's bridged to Swift, you can call with any UIView instance.

enter image description here

EDIT:

After a little research, it seems you can declare your func like this

func myFunc<T:UIView where T:UITextFieldDelegate>(view:T) { ... }

Upvotes: 2

Rajesh
Rajesh

Reputation: 10434

Make a sub class of UIView and let the SubClassedView conforms to UITextFieldDelegate

In traditional way

@interface SubClassedView:UIView <UITextFieldDelegate>

@end

in swift

class SubClassedView:UIView, UITextFieldDelegate {

}

Upvotes: 1

Related Questions