Variable with the "self" value

Good evening to everyone,

junior after long research is unable to find out what is going on in this piece of code:

socket.delegate = self

Could you please help with understanding what is in general happening after setting a value "self" to the variable? Self keyword should refer to the object itself. But how can i set the object itself to the value of that object / why would i do that?

Thank you for your time.


/* In the case of need code explanation to answer the question:

Code is used from "Starscream" library handling WebSocket protocol connections.

Variable "socket" holds an instance of Websocket() class:

var socket: WebSocket!
socket = WebSocket(request: request)

Parameter "delegate" is a weak variable with optional type "WebSocketDelegate?", where "WebSocketDelegate" is the protocol with one method:

public weak var delegate: WebSocketDelegate?

public protocol WebSocketDelegate: class {
func didReceive(event: WebSocketEvent, client: WebSocket)


self means “the instance whose method is currently running”, rather than “the current value of the property being assigned to” or “the instance that property lives on”. So in this case the socket’s delegate is being set to the object that owns the socket (a SocketController or whatever) so that that object can get callbacks from the socket.

1 Like

Hello jrose, after several tests, then compared to this clear explanation “the instance whose method is currently running” i finally get the "self" type.. thank you very much!