Swift语言中的Delegate

Swift语言官方教程中,针对Delegate有这么一段描述:

delegate is an object that acts on behalf of, or in coordination with, another object. The delegating object—in this case, the text field—keeps a reference to the other object—the delegate—and at the appropriate time, the delegating object sends a message to the delegate. The message tells the delegate about an event that the delegating object is about to handle or has just handled. The delegate may respond by for example, updating the appearance or state of itself or of other objects in the app, or returning a value that affects how an impending event is handled.

大概意思是:一个Delegate就是一个对象,它可以根据其它对象的行为做出反应。指派Delegate的对象(本例中就是text field)会保留指向Delegate的一个引用,并且在适当的时机向Delegate发送一条消息。这条消息告诉Delegate它的委托人将要处理或者已经处理完一个事件。接收消息的Delegate可以做出反应,例如更新自己的外观或者改变自己或者其它对象的状态,亦或者返回可以影响即将发生事件的值。

A text field’s delegate communicates with the text field while its text is being edited, and knows when important events occur—such as when a user starts or stops editing text. The delegate can use this information to save or clear data at the right time, dismiss the keyboard, and so on.

作为Text Field的Delegate,它可以在Text Field的文本在编辑状态下时与Text Field保持沟通,并且知晓重要的事件何时发生——例如用户开始或者结束编辑文本。Delegate可以利用这些消息在合适的时机保存或清除数据、收回键盘等等。