Home > Articles > Programming > General Programming/Other Languages

Introducing Swift Syntax and Data Types

  • Print
  • + Share This
This chapter from Swift for the Really Impatient introduces the basic syntax and data types of Swift.
This chapter is from the book

This chapter is from the book

Swift is a new programming language developed by Apple that was released to developers at WWDC 2014. Swift can be used to develop applications for Apple’s iOS and OS X platforms. It is designed to work with, but eventually replace, Objective-C, the language originally used for developing applications on Apple’s platforms.

Apple has a number of goals for Swift:

  • Make app development easier, with modern language features.
  • Produce safer code by preventing the most common programming errors.
  • Create easy-to-read code with clear and expressive syntax.
  • Be compatible with existing Objective-C frameworks, including the Cocoa and Cocoa Touch frameworks.

This chapter introduces the basic syntax of Swift and lays the foundation you’ll need for the rest of the book.

These are the key points in this chapter:

  • You use var to declare a variable and let to declare a constant.
  • You execute code conditionally with if or switch constructs.
  • You repeat code segments by looping with for, for-in, while, and do-while loop constructs.
  • The basic data types are implemented as structs, which are passed by value in code.
  • Since the basic types are structs, they may have additional properties or methods available.
  • Arrays and dictionaries in Swift are more powerful collection types than their Objective-C counterparts.

1.1 Basic Syntax

When you learn a new language, the first complete program you’re likely to see is the famous “Hello World” example. In Swift, this program consists of just one line:

println("Hello World")

The first thing you should notice here is what you don’t see. The code jumps right into the guts of the program. You don’t need to set anything up to get started, include or import a standard library, set up an initial main() function to be called by the system, or even include a semicolon at the end of each line.

1.1.1 Variables and Constants

A program that only prints a static line of text isn’t very useful. For a program to be useful, it needs to be able to work with data, using variables and constants. As their names imply, variables have contents that may change throughout the execution of the code, while constants cannot be changed after they’re initialized. Variables are said to be mutable; constants are immutable.

In Swift, you declare a variable by using the var keyword, and you declare a constant by using the let keyword. This applies for all data types in Swift and is different from Objective-C, where the type itself indicates whether it is mutable or not, such as NSArray versus NSMutableArray. With Swift, the mutable version of an object is the same type as the immutable version—not a subclass.

For the rest of this chapter, what we say about variables applies equally to constants (provided that we’re not talking about mutating data).

Swift is a strongly typed language, which means that every variable is set to a specific type at compile time, and it can only contain values of that type throughout its lifetime.

Two common types are Int and Float. (We’ll get into their details a little later.) If you set a variable to be of type Int, it can only ever store Int values; it can never be coerced into storing a Float. Types can never be implicitly converted into other types. This means, for example, that you cannot add an Int to a Float. If you need to add two numbers together, you need to make sure they’re the same type or explicitly convert one to the other. This is part of what makes Swift a safe language: The compiler prevents you from mixing types and possibly producing unexpected results.

To see the dangers involved in mixing types, consider this C code:

int intValue = 0;
float floatValue = 2.5;
int totalValue = intValue + floatValue;

This code adds an int and a float together. What would total be equal to here? Since the total is an int, it is unable to store the decimal portion of the floatValue variable. floatValue must first be implicitly converted to an int before it can be added to intValue and stored in totalValue. In this case, is the developer expecting the compiler to round floatValue to 3, or is she expecting it to just drop the decimal portion and instead add 2? Swift avoids this type of ambiguity by producing a compile-time error here, forcing you to tell it exactly what you want to happen. This is one way Swift avoids common programming errors.

You need to give variables and constants names so that you can refer to them in code. Names in Swift can be composed of most characters, including Unicode characters. While it’s possible to use emoji and similar characters as variable names, you should rarely, if ever, actually do it. Here is the minimum code for declaring a variable:

var itemCount: Int

This code declares a variable named itemCount of type Int. A variable must be set to an initial value before you can use it. You can do this when the variable is declared, like this:

var itemCount: Int = 0

or you can do it at some later point, as long as you do it before you attempt to read the value.

Swift has a feature called type inference. If the compiler has enough information from the initial value you set to infer the type, you can omit the type of the variable when you declare it. For example, if your variable is going to be an Int, you can declare it like this:

var itemCount = 0

Because 0 is an Int, itemCount is inferred to be an Int. This is exactly the same as the example above. The compiler generates exactly the same machine code.

If the variable’s initial value is set to the return value of a function, the compiler will infer the type to be the same as the return value’s type.

Given a function numberOfItems() that returns an Int and the following line:

var itemCount = numberOfItems()

the compiler will infer itemCount to be of type Int.

Since the compiler generates exactly the same code whether you explicitly set the type or use type inference to let the compiler set the type for you, there is no advantage or disadvantage to either method at run time. Of course, if you need to explicitly set the type, you have no option. But in cases where the compiler can infer the type, it’s up to you whether to let the compiler do so or whether you explicitly set the type anyway. There are two things to consider when making this decision. The first is readability. If, when you use type inference, the type of the variable would still be clear to a future reader of the code, by all means save some keystrokes and use type inference. If the initial value being set is the return value of some uncommon function, it may be clearer to the future reader if you explicitly set the type. When reading the code at a later date, you don’t want to have to look up what a function returns just to determine a variable’s type.

The second reason you might want to explicitly set a type when it can be inferred is to add an additional safety check. This ensures that the type you’re expecting the variable to be and the type being set match. If there’s a mismatch, you get a compile-time error and can make the necessary corrections.

1.1.2 String Interpolation

You’ve already seen how to print a line of text to the console by using the println command. You can add variables, constants, and other expressions to the output by using string interpolation. You do so by including variables and expressions directly in the string literal, surrounded by parentheses and escaped with a backslash:

var fileCount = 99
println("There are \(fileCount) files in your folder")
//outputs: There are 99 files in your folder

This doesn’t apply just to println. You can use it anywhere a string literal is used:

var firstName = "Geoff"
var lastName = "Cawthorne"
var username = "\(firstName)\(lastName)\(arc4random() % 500)"
//username: GeoffCawthorne253

1.1.3 Control Flow

All but the simplest of programs require some sort of logic to determine what actions should be taken. Decisions must be made based on the information the program has available. Logic such as “If this, do that” or “Do this x many times” determines the flow of an app and, thus, its result.

Conditionals

Swift offers both if and switch constructs for you to execute code conditionally.

Using if is the simpler of the two constructs and closely follows what you’re used to in Objective-C. There are a few differences you need to be aware of, however. The first difference continues Swift’s theme of reducing unnecessary syntax: Swift does not require you to surround test expressions with parentheses, though you may, if you desire. The second difference is that braces are required around the conditional code. Third, the test expression must explicitly result in a true or false answer; an Int variable with a value of 0 is not implicitly evaluated as false, nor is a value of anything else implicitly evaluated as true.

Here is a minimal example:

var daysUntilEvent: Int = calculateDaysUntilEvent()
if daysUntilEvent > 0 {
    println("There is still time to buy a gift")
}

You can chain together multiple ifs with the else keyword:

var daysUntilEvent: Int = calculateDaysUntilEvent()
if daysUntilEvent > 0 {
    println("There is still time to buy a gift")
}
else if daysUntilEvent < 0 {
    println("You missed it, better pick up a belated card")
}
else {
    println("Better pick up the gift on the way")
}

The switch construct is an alternative to if statements. It is based on what you’ve used in Objective-C, but in Swift, it is much more powerful. There are two important differences you need to consider when using a switch in Swift. The first is that every possible option must be covered. A default case can be used to accomplish this requirement. The second difference is a major change in how cases are handled. In C-based languages, you need to include a break statement at the end of each case, or execution will continue with the next case. This has been the source of many errors over time. To prevent these errors in Swift, the design was changed to automatically break when the next case begins. Some algorithms may require the old behavior, so it is available to you through the use of the fallthrough keyword.

Here’s a basic example of a switch in use:

var numberOfItemsInCart: Int = calculateNumberOfItemsInCart()
switch numberOfItemsInCart {
case 0:
    println("Cart is Empty")
case 1:
    println("1 item in cart, standard shipping applies")
default:
    println("\(numberOfItemsInCart) items, you quality for free shipping")
}

We’ll cover advanced switch usage in Chapter 2, “Diving Deeper into Swift’s Syntax.”

Loops

In Swift, for, for-in, while, and do-while are used for looping. These are similar to what you’re used to in Objective-C, with only slight differences in the syntax.

Here is a basic for example:

for var i = 0; i < 10; ++i {
    println("i = \(i)")
}

Just as with if statements, you can omit the parentheses. In this example, i is implicitly declared as an Int. The loop will iterate while i < 10, and it’s incremented by 1 at the end of each iteration.

Another form of the for loop is the for-in loop. This lets you iterate through each item in a collection, such as an array or a range.

Swift has two new range operators for creating ranges that can be used with for-in loops. The ..< operator is the half-open range operator; it includes the value on the left side but not the value on the right side. Here’s an example that iterates 10 times, with i starting as 0 and ending as 9:

for i in 0 ..< 10 {
    println("i = \(i)")
}

The ... operator is the inclusive range operator. It includes the values on both sides. This example iterates 10 times, with i starting as 1 and ending as 10:

for i in 1 ... 10 {
    println("i = \(i)")
}

When you use a for-in loop to iterate through a collection such as an Array, it looks like this:

var itemIds: [Int] = generateItemIds()
for itemId in itemIds {
    println("itemId: \(itemId)")
}

The while loop iterates for as long as the test condition is true. If the test condition is false at the start, the loop doesn’t iterate at all, and it is just skipped entirely. For instance, this example will never actually print 100% complete since the test condition becomes false once percentComplete == 100:

var percentComplete: Float = calculatePercentComplete()
while percentComplete < 100 {
    println("\(percentComplete)% complete")
    percentComplete = calculatePercentComplete()
}

If you change this to a do-while loop, the test condition is evaluated at the end of the loop. This guarantees that the loop will iterate at least once and also means it will iterate a final time when the test condition fails (which could be the first iteration). This version updates the display one final time once the task being monitored is complete:

var percentComplete: Float = 0.0
do {
    percentComplete = calculatePercentComplete()
    println("\(percentComplete)% complete")
} while percentComplete < 100

When using a loop, there are times when you need to adjust the iterations by either quitting iteration altogether or skipping a single iteration. Just as in Objective-C, there are two keywords you can use for these purposes: break and continue. You use break to immediately jump out of the loop and cancel any further iterations:

var percentComplete: Float = 0.0
do {
    percentComplete = calculatePercentComplete()
    if taskCancelled() {
        println("cancelled")
        break
    }
    println("\(percentComplete)% complete")
} while percentComplete < 100

You use continue to end the current iteration and immediately start the next one:

var filesToDownload: [SomeFileClass] = filesNeeded()
for file in filesToDownload {
    if file.alreadyDownloaded {
        continue
    }

    file.download()
}

With nested loops, break and continue affect only the inner loop. Swift has a powerful feature that Objective-C does not have: You can add labels to your loops and then specify which loop you would like to break or continue out of. A label consists of the name followed by a colon in front of the loop keyword:

var folders: [SomeFolderClass] = foldersToProcess()
outer: for folder in folders {
    inner: for file in folder.files {
        if shouldCancel() {
            break outer
        }

        file.process()
    }
}
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020