Swift 5: Do You Really Know About Variables?
Hi iOS Developers,
Do you still remember the “Hello World” project you wrote? What was the first topic you learned for iOS development? Most people began their iOS development by declaring their first variable and function, which are the most fundamental and mandatory components of all the applications. Do you really know about variables? Let’s find out!
What is a variable?
A variable is a data container that stores and/or retrieves data.
How to declare a variable?
String, Int, Double and Bool, etc.:
var name = "Steve"
var age: Int = 35
var height: Double = 8.9
var isTall: Bool = {
return height > 7
}()These are different ways to declare variables.
Variable Naming Convention:
1. Do not use abbreviations.
For example, use mutableVariable instead of mutVar , use titleLabel instead of ttlLbl . The name should be descriptive and clear. As a test of this, try showing your code to another developer. See if they know instantly what the variable is about without guessing.
2. Start with singular auxiliaries for boolean names.
It may not make sense if the variable is being used within the class. To check this, take a step back, and see what the booleans look like when related to their object. That will help them make more sense.
Here is a bad example:
struct User {
var verifiedEmail: Bool
var activated: Bool
var haveAJob: Bool
}let user = User(verifiedEmail: false, activated: true, haveAJob: true)When you access the properties, they will look like this:
user.verifiedEmail
user.activated
user.haveAJobWhen you read them out loud, you will realize that they have grammar mistakes and are unclear about the properties' purpose.
Here is a better example:
struct User {
var didVerifyEmail: Bool
var isActivated: Bool
var hasAJob: Bool
}When you read this example now, they make much more sense.
user.didVerifyEmail
user.isActivated
user.hasAJobWhat are the differences between a variable and a property?
They are basically the same thing. When we talk about the data container itself, we call it a “variable.” When we talk about the data container of an object, we call it a “property.”
Let’s take a look at an example:
class User {
var name: String
init(name: String) {
self.name = name
}
}name is a variable of type String.
let user = User(name: "Dylan")
user.nameuser has a name property.
Custom Getter and Setter
Swift allows us to customize the getter and setter of a variable.
Default:
var name: Stringname = "Dylan"
print(name)In this example, we are setting the value to name and retrieving the value from name.
Custom:
var contactDictionary = [String: String]()var name: String? {
get { return contactDictionary["name"] }
set { contactDictionary["name"] = newValue }
}name = "Dylan"
print(name)Now, when we get the value of name , it will return a value that’s from the contactDictionary , when we set the value to name , it sets the value to contactDictionary .
Computed Variable vs. Stored Variable
Bot computed variables and stored variables have a setter and gett. In addition, a computed allows the variable to perform computations before returning and storing the value.
For example:
var subtotal = 12.9
var tax = 1.95var total: Double {
subtotal + tax
}print(total) // 14.85In this example, both subtotal and tax are stored variables. They store value to themselves and retrieve the values when they got called.
On the other hand, total is a computed variable. It doesn’t have a setter which means values can’t be assigned to it. Whenever it gets called, it sums the values of subtotal and tax . If subtotal or tax is changed later, the returned value of total will be changed too.
Why do we use computed variables when we have non-void functions?
Let’s take a look at the previous example.
var subtotal = 12.9
var tax = 1.95var total: Double {
subtotal + tax
}func getTotal() -> Double {
subtotal + tax
}print(total) // 14.85
print(getTotal()) // 14.85Both total and getTotal() return the same value, and they look very similar. Which one should we use in this case? We should use the computed total variable because subtotal and tax are already provided by the class, sousing a computed variable is enough. We should consider using non-void functions for dynamic values.
For instance:
var subtotal = 12.9
var tax = 1.95var total: Double {
subtotal + tax
}func getTotal(with deliveryFees: Double) -> Double {
subtotal + tax + deliveryFees
}print(total) // 14.85print(getTotal(with: 5.68)) // 20.53
print(getTotal(with: 3.36)) // 18.21
print(getTotal(with: 2.8)) // 17.65Now, we can pass a dynamic deliveryFees value to the getTotal() function, but we could also accomplish this with the computed total variable.
Function Type Variables
Variables can hold many types of data, including functions. The declaration is very similar to how we declare a String variable.
class Order {
var getTotal: ((Double) -> Double)?
}class Store {
let subtotal = 12.95
let tax = 2.34 func getTotal(with deliveryFees: Double) -> Double {
subtotal + tax + deliveryFees
}
}let order = Order()
let store = Store()order.getTotal = store.getTotalprint(order.getTotal!(4.5))By creating the var getTotal: ((Double) -> Double)? variable in Order and passing the value of getTotal(with deliveryFees: Double) -> Double from Store to Order , we can use the getTotal() in an Order object.
Conclusion
As one of the most fundamental components of Swift, variables play an essential role in iOS development. There are still many other types of variables out there, but I can’t cover them all in one article. I hope you enjoyed this article and I’ll see you next time :)






