Let's begin the refactoring of our view controller, as follows:
protocol ComposeViewControllerDelegate: AnyObject {
func composeViewController(_ controller: ComposeViewController,
attemptToSend message: String)
}
class ComposeViewController: UIViewController {
enum State {
case `default`
case error(Error)
case sending
}
private var textView = UITextView()
private var sendButton = UIButton()
weak var delegate: ComposeViewControllerDelegate?
var state: State = .default {
didSet { /* todo handle state */ }
}
func sendTapped(sender: UIButton) {
delegate?.composeViewController(self, attemptToSend: textView.text)
}
}
The view controller is now completely focused on managing views. It is easier to extend and to manage. If we have more actions to add in the future, such as picking a photo or gif, it is easier to add this feature without cluttering the code for the composition message.