Improper type assignation - Swift

Improper type assignation - Swift

Need

Enforce proper type assignment and declaration in the source code

Context

  • Usage of Swift for iOS and macOS app development

Description

Non compliant code

        var someVariable = 42
someVariable = "Hello, World!"
        
        

In the above Swift code, we have a variable someVariable which is initially assigned an integer value 42. Later, the same variable is assigned a string "Hello, World!". This is an example of improper type assignment.

In Swift, the type of a variable is inferred by the compiler at the time of its initialization. Therefore, once a variable is initialized with a certain type, it cannot be assigned a value of a different type later. In our case, someVariable is inferred to be of type Int when it is initialized with 42. Hence, assigning a string to it later is not valid.

This kind of improper type assignment can lead to runtime errors, inefficient code (as the compiler has to identify the variable's data type every time), and can make the code harder to understand and maintain.

Steps

  • Identify the specific data type that the variable should hold.
  • Declare the variable with the appropriate data type.
  • Assign the initial value to the variable using the correct data type.
  • Ensure that subsequent assignments to the variable are of the same data type.

Compliant code

        var someVariable: Int = 42
        
        

In the original code, someVariable was declared without a specific type, which means it could hold any type of value. This is a type of vulnerability because it can lead to unexpected behavior and inefficiencies in the code.

In Swift, it's a good practice to always specify the type of the variable when you declare it. This way, the compiler knows exactly what type of data to expect, and it can optimize the code accordingly.

In the fixed code, someVariable is declared as an Int, and it's assigned the initial value of 42. This means that someVariable can now only hold integer values. If you try to assign a value of a different type to someVariable (like a string or a float), the compiler will give you an error. This helps prevent bugs and makes the code more efficient and easier to understand.

Please note that once a variable's type is set, it cannot be changed. So, if you need someVariable to hold a string value later in the code, you would need to declare a new variable of type String.

References