avatarSwiftos

Summary

This article provides an in-depth exploration of variables in Swift 5, covering their declaration, naming conventions, differences between variables and properties, custom getters and setters, computed versus stored variables, the use of function type variables, and concludes with a call to action for further engagement with the author's content.

Abstract

The article "Swift 5: Do You Really Know About Variables?" by Dylan C. Fei is a comprehensive guide aimed at iOS developers who wish to strengthen their foundational understanding of variables in Swift. It begins by reminding readers of the importance of variables as a starting point in iOS development and then delves into the specifics of declaring variables with different data types, such as String, Int, Double, and Bool. The author emphasizes the significance of clear and descriptive naming conventions for variables, particularly for boolean types, and illustrates the distinction between variables and properties within the context of object-oriented programming.

Fei also demonstrates how to implement custom getters and setters, allowing developers to perform additional logic when accessing or modifying a variable's value. He differentiates between computed variables, which perform on-the-fly calculations, and stored variables, which simply hold values. The article argues for the use of computed variables when dynamic calculations are needed, as opposed to non-void functions, which are better suited for operations involving external parameters.

Additionally, the author introduces the concept of function type variables, showcasing how variables in Swift can store functions as values, thus enabling more flexible and modular code design. The article concludes with an invitation for readers to engage with the content by clapping, following, and suggesting topics for future articles, and it teases related content on protocol-oriented programming and the use of protocols in Swift.

Opinions

  • The author believes that a clear and descriptive naming convention is crucial for variable names to ensure code clarity and maintainability.
  • Fei suggests that boolean variable names should start with auxiliary verbs to make their purpose clear when used within a class context.
  • The article posits that computed variables are a cleaner solution for certain calculations compared to non-void functions, particularly when the computation is directly related to the object's properties.
  • There is an

Swift 5: Do You Really Know About Variables?

Photo by Giorgio Trovato on Unsplash

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.haveAJob

When 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.hasAJob

What 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.name

user has a name property.

Custom Getter and Setter

Swift allows us to customize the getter and setter of a variable.

Default:

var name: String
name = "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.95
var total: Double {
    subtotal + tax
}
print(total) // 14.85

In 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.95
var total: Double {
    subtotal + tax
}
func getTotal() -> Double {
    subtotal + tax
}
print(total) // 14.85
print(getTotal()) // 14.85

Both 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.95
var total: Double {
    subtotal + tax
}
func getTotal(with deliveryFees: Double) -> Double {
    subtotal + tax + deliveryFees
}
print(total) // 14.85
print(getTotal(with: 5.68)) // 20.53
print(getTotal(with: 3.36)) // 18.21
print(getTotal(with: 2.8)) // 17.65

Now, 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.getTotal
print(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 :)

Please clap if you enjoy this article. Follow me, and comment below on what topics you would like me to cover in subsequent articles :)

YOU MAY ALSO BE INTERESTED IN:

Swift
iOS App Development
Swift Programming
iOS Development
iOS
Recommended from ReadMedium