I am reading through the Encoding and Decoding Custom Types article, and I am seeing to encoder: Encoder
and from decoder: Decoder
throughout the examples.
I am new to Swift, and it isn't really clear to me why it is to encoder: Encoder
and not just encoder: Encoder
.
Here is a longer snippet for more context:
extension Coordinate: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(latitude, forKey: .latitude)
try container.encode(longitude, forKey: .longitude)
var additionalInfo = container.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .additionalInfo)
try additionalInfo.encode(elevation, forKey: .elevation)
}
}
What is the purpose of to
and from
within these examples?
I have been trying to find an answer to this question, but searching for "what is the purpose of to in swift" and other variants has been remarkably unsuccessful.
For the encode() function, to
is known as an Argument Label, and is what the caller of the function uses when passing a parameter to the encode() function.
Within the encode() function body, the to
Argument Label is not used to refer to the parameter, but its parameter name encoder
is used instead.
to
and from
are not reserved keywords. Argument Labels can be used to help make your code more readable.
For more information, see Function Argument Labels and Parameter Names