I am wondering if using static structs to mutate data in Swift is not a proper practice. I had a coding challenge for an interview and in the feedback for my work they said that "We didn't understand why you had static structs that mutated data."
.
For a little background into my implementation of the coding challenge, the project was to create a clone of the iOS Calculator app. At a high level I had 3 major pieces:
ViewController
to handle button clicks and UI formattingstruct
handler for doing the computations- Custom
UILabel
that formatted the number for the output
Based off of posts I have read online, I always thought a struct
was preferred over a class
when possible because copying data is safer than having multiple reference points to a single instance.
I also decided to make the properties and functions in the class static
so that I did not have to instantiate and pass around the handler in the view controller to access them. There would only ever be one handler that needed to retain data throughout the session based on the user's input.
Below is a snippet of how this handler was structured.
struct CalculationHandler {
/// Will be the first number included in the operation
static var firstEntry:Double?
/// Will be the second number included in the operation
static var secondEntry: Double?
/// Operation that is next to be executed
static var currentCalculation:CalculationType = .none
/// Returns calculated value based on firstEntry, secondEntry, and CalculationType
static func calculate(_ calculationType:CalculationType) -> Double? { ... }
This CalculationHandler
was called and used in the button clicks of the ViewController
, like below:
if let value = CalculationHandler.calculate(.addition) {
outputLabel.calculatedValue = "\(value)"
}
Can anyone explain why implementing a struct
with static
properties/functions is not a good practice for this use-case?