Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Swift 5.3

You're reading from   Mastering Swift 5.3 Upgrade your knowledge and become an expert in the latest version of the Swift programming language

Arrow left icon
Product type Paperback
Published in Nov 2020
Publisher Packt
ISBN-13 9781800562158
Length 418 pages
Edition 6th Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (23) Chapters Close

Preface 1. Taking the First Steps with Swift 2. Swift Documentation and Installing Swift FREE CHAPTER 3. Learning about Variables, Constants, Strings, and Operators 4. Optional Types 5. Using Swift Collections 6. Control Flow 7. Functions 8. Classes, Structures, and Protocols 9. Protocols and Protocol Extensions 10. Protocol-Oriented Design 11. Generics 12. Error Handling and Availability 13. Custom Subscripting 14. Working with Closures 15. Advanced and Custom Operators 16. Concurrency and Parallelism in Swift 17. Custom Value Types 18. Memory Management 19. Swift Formatting and Style Guide 20. Adopting Design Patterns in Swift 21. Other Books You May Enjoy
22. Index

Swift language syntax

If you are an Objective-C developer, and you are not familiar with modern languages such as Python or Ruby, the code in the previous screenshots may have looked pretty strange. The Swift language syntax is a huge departure from Objective-C, which was based largely on Smalltalk and C.

The Swift language uses modern concepts and syntax to create very concise and readable code. There is also a heavy emphasis on eliminating common programming mistakes.

Before we get into the Swift language itself, let's look at some of the basic syntax of the Swift language.

Comments

Writing comments in Swift code is a little different from writing comments in Objective-C code. We can still use double slash (//) for single-line comments and /** and */ for multiline comments; however, if we want to use the comments to also document our code, we need to use the triple slash (///) or multiline comment block.

You can auto-generate a comment template based on your signature of the method/function with Xcode by highlighting it and pushing command + option + / together.

To document our code, we generally use fields that Xcode recognizes. These fields are as follows:

  • Parameter: When we start a line with parameter {param name}:, Xcode recognizes this as the description of a parameter.
  • Return: When we start a line with return:, Xcode recognizes this as the description of the return value.
  • Throws: When we start a line with throws:, Xcode recognizes this as a description of any errors that this method may throw.

The following playground shows examples of both single-line and multiline comments and how to use the comment fields:

A screenshot of a cell phone

Description automatically generated

Figure 1.8: Adding comments in a playground

To write good comments, I would recommend using single-line comments within a function to give quick one-line explanations of your code. We then use multiline comments outside functions and classes to explain what the function and class do. The preceding playground shows a good way to use comments. By using proper documentation, as we did in the preceding screenshot, we can use the documentation feature within Xcode. If we hold down the option key and then click on the function name anywhere in our code, Xcode will display a popup with a description of the function.

The following screenshot shows what that popup would look like:

A screenshot of a computer screen

Description automatically generated

Figure 1.9: Xcode documentation on functions

We can see that the documentation contains five fields. These fields are as follows:

  • Declaration: This is the function's declaration.
  • Parameters: This is the description of the function's as they appear in the comments. The parameter descriptions are prefixed with the Parameters: tag in the comment section.
  • Throws: The throws description is prefixed with the throws tag and describes what errors are thrown by the methods.
  • Returns: The returns description is prefixed with the returns: tag in the comment section.
  • Declared In: This is the file that the function is declared in so that we can easily find it.

There are significantly more fields that we can add to our comments. You can find the complete list on Apple's site: https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html.

If you are developing for the Linux platform, I would still recommend using Apple's documentation guidelines because, as other Swift IDEs are developed, I believe they will support the same guidelines.

Semicolons

You may have noticed, from the code samples so far, that we are not using semicolons at the end of lines. Semicolons are optional in Swift; therefore, both lines in the following playground are valid in Swift:

A screenshot of a computer screen

Description automatically generated

Figure 1.10: The use of semicolons in Swift

For style purposes, it is strongly recommended that you do not use semicolons in your Swift code. If you are really set on using semicolons, be consistent and use them on every line of code; however, there is no warning if you forget them.

I will stress this again: it is recommended that you do not use semicolons in Swift.

Parentheses

In Swift, parentheses around conditional statements are optional; for example, both if statements in the following playground are valid:

A screenshot of a computer screen

Description automatically generated

Figure 1.11: Parentheses in Swift

For style purposes, it is recommended that you do not include parentheses in your code unless you have multiple conditional statements on the same line. For readability purposes, it is good practice to put parentheses around individual conditional statements that are on the same line.

Curly brackets

In Swift, unlike most other languages, a curly bracket is required after conditional or loop statements. This is one of the safety features that is built into Swift. Arguably, there have been numerous security bugs that could have been prevented if the developer had used curly brackets. These bugs could have also been prevented by other means, such as unit testing and code reviews, but requiring developers to use curly brackets, in my opinion, is a good security standard.

The following playground shows you the error you get if you forget to include curly brackets:

A screenshot of a computer screen

Description automatically generated

Figure 1.12: Curly brackets in Swift

An assignment operator does not return a value

In most other languages, the following line of code is valid, but it probably isn't what the developer meant to do:

if (x = 1) {}

In Swift, this statement is not valid. Using an assignment operator (=) in a conditional statement (if, while, and guard) will throw an error. This is another safety feature built into Swift. It prevents the developer from forgetting the second equals sign (=) in a comparison statement. This error is shown in the following playground:

A screenshot of a computer screen

Description automatically generated

Figure 1.13: Assignment operators in Swift

Spaces are optional in conditional and assignment statements

For both conditional (if and while) and assignment (=) statements, the white spaces are optional. Therefore, in the following playground, both the i and j blocks of code are valid:

A screenshot of a computer screen

Description automatically generated

Figure 1.14: Spaces in Swift

For style purposes, I recommend adding the white spaces as the j block shows (for readability), but as long as you pick one style and are consistent, either style is acceptable.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime