I want an extension for two classes UITextField
and UITextView
and the code is identical, but I have trouble coming up with an extension that will work for them both.
I am using ReactiveCocoa and I currently have this
import UIKit
import ReactiveCocoa
import enum Result.NoError
typealias NoError = Result.NoError
// How to DRY up this code?
extension UITextField {
func textSignalProducer() -> SignalProducer<String, NoError> {
return self.rac_textSignal()
.toSignalProducer()
.map { $0 as! String }
.flatMapError { error in SignalProducer<String, NoError>(value: "") }
}
}
extension UITextView {
func textSignalProducer() -> SignalProducer<String, NoError> {
return self.rac_textSignal()
.toSignalProducer()
.map { $0 as! String }
.flatMapError { error in SignalProducer<String, NoError>(value: "") }
}
}
How would I write an extension that would work for both? I was trying to do something like
protocol TextSignalProducer {}
extension TextSignalProducer where Self: ???? {
// Same code as is duplicated in both current extensions...
}
but I have no idea how to specify Self
as either UITextField
or UITextView
. Something like where Self == UITextField || Self == UITextView
would probably make this possible.
Is there a nice way to accomplish what I want to try? Is this really necessary (I don't know the naming conventions for protocols/extensions)
import UIKit
import ReactiveCocoa
import enum Result.NoError
typealias NoError = Result.NoError
protocol TextSignal {
func rac_textSignal() -> RACSignal!
}
extension UITextField: TextSignal, TextSignalProducer {}
extension UITextView: TextSignal, TextSignalProducer {}
protocol TextSignalProducer {}
extension TextSignalProducer where Self: TextSignal {
func textSignalProducer() -> SignalProducer<String, NoError> {
return self.rac_textSignal()
.toSignalProducer()
.map { $0 as! String }
.flatMapError { error in SignalProducer<String, NoError>(value: "") }
}
}
I am using Swift 2.1, Xcode 7.2 and ReactiveCocoa 4.0.1