In the Swift programing language, there are two ways to declare a variable; You can declare a variable as immutable using a syntax like let x = 1.0 or you can declare it mutable using var x = 1.0. There are some weirdnesses to the mutability of objects but for a numeric parameter to a function, such as an Int or Double, you simply cannot change the value within the function.
func setGearRatio( link1: Link, link2: Link, size1: Double, size2: Double, useSizeAsSize: Bool, sizeIsDiameter: Bool, type: GearConnection.ConnectionType, internalGear: Bool, fromUI: Bool ) -> Bool {
In the code above, if the caller passes in a size1 value then it is used with the size2 value to calculate a ratio and the specific values themselves don’t have meaning. But that is not the case if both the useSizeAsSize and sizeIsDiameter values are true. If the passed-in sizes are diameters and the sizes are supposed to represent the actual sizes of the gears (and aren’t used only to calculate a ratio) then the internal value needs to be converted to a radius for storage. It’s far easier to always store the radius regardless of what the user is entering in the user interface.
Swift treats all function parameters as immutable (as if “let” was used). There is no way to change size1 or size2 because that causes an error. And code that declares some other variables, like useSize1 and useSize2 is error-prone since someone might later not notice and use the original size1 and size2 values. But Swift has a cool feature where it is not an error to declare variables that have the same name as parameters:
var size1 = useSizeAsSize && sizeIsDiameter ? size1 / 2.0 : size1
var size2 = useSizeAsSize && sizeIsDiameter ? size2 / 2.0 : size2
This essentially changes the parameter values but does so in a way that is more obvious and clear. It also makes it clear that any changes to these variables do not propagate back out of this function and change the caller’s copy of the variable. With an integer value, a programmer might not expect the caller’s copy of the value to change. But with a String object, it is not quite as clear. This syntax makes it very clear that a new copy of the parameter is being created. This syntax has the side benefit, and a most important one, to keep anyone from writing code in the function that uses the original unchanged parameter, as might happen if some new adjusted variable is declared in addition to the original variable.
It is features like this that make Swift interesting to me. It’s hard to remember these things when I’m switching between Swift, C++, Java, and C# all the time. If I had to pick a language to use for all of my programming, I think that it would be Swift.