I'm trying to catch up with this protocol-oriented-programming coolness using Swift 2 but I'm currently quite lost.
I'm trying to apply the theory to practical use cases so let's start with the most obvious:
Let's say I have a UITextField
and I want to have many protocols (e.g. phone, numeric, lengthLimited…) that conform to UITextFieldDelegate
and override the textField:shouldChangeCharactersInRange:replacementString
method to accomplish the desired behavior.
Is it even possible to have a "Extensions.swift" file with this extensions and assign the desired protocols to a UITextField
(e.g. numeric, lengthLimited)? That would be very useful. If so, is there a way to assign a protocol to, let's say, a UITextField
outlet or I'd need to subclass a UITextField
and make it conform the desired protocols? If this is the case, then I don't see too much advantage in using protocols extensions over good old subclassing.
The case you're describing doesn't make a lot of sense as a protocol or as extensions. You definitely can't apply an extension to a specific instance of a class.
The two ways to implement this would be inheritance (subclassing) or composition (helpers). Subclassing you likely understand. To make a helper, you just write the function that you'd want and reuse it:
func numericTextField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// The code you'd want for numerics
}
And then you'd just call that shared code from your actual delegate's textField(_:shouldChangeCharactersInRange:replacementString:)
.
func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return numericTextField(textField, shouldChangeCharactersInRange: range, replacementString: String)
}
You might choose to simplify the function's signature if you don't really need all those parameters of course.
In general, composition is the more flexible approach. Just write some functions and call them.
Extensions and protocols are powerful and important tools. They're just not related to this problem.