Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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

You're reading from   Mastering Swift 5 Deep dive into the latest edition of the Swift programming language

Arrow left icon
Product type Paperback
Published in Apr 2019
Publisher Packt
ISBN-13 9781789139860
Length 370 pages
Edition 5th Edition
Languages
Tools
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 (20) Chapters Close

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

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 the double slash // for single-line comments and the /** 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.

Xcode will also auto-generate a comment template based on your signature of the method/function 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 the 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:

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 the description of the function.

The following screenshot shows what that popup would look like:

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

  • Declaration: This is the function's declaration.
  • Description: This is the description of the function as it appears in the comments Parameters. 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 return 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. The semicolons are optional in Swift; therefore, both lines in the following playground are valid 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:

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 the individual conditional statements that are on the same line.

Curly brackets

In Swift, unlike most other languages, the 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 may 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:

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:

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 the j blocks of code are valid:

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.

You have been reading a chapter from
Mastering Swift 5 - Fifth Edition
Published in: Apr 2019
Publisher: Packt
ISBN-13: 9781789139860
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
Banner background image