Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

1.2 Basic Data Types

Swift has a standard set of basic data types for storing numbers, strings, and Boolean values.

By convention, types in Swift are named using camel case notation. Unlike in Objective-C, there is no prefix (NS, CG, etc.) on the standard type names.

1.2.1 Int

For storing integer values, the basic type is Int. It is 32 bits deep on 32-bit devices and 64 bits deep on 64-bit devices.

You can access the minimum and maximum values the type can store by using the min and max static properties:

//output on 32-bit device: -2147483648
//output on 64-bit device: -9223372036854775808

//output on 32-bit device: 2147483647
//output on 64-bit device: 9223372036854775807

When you need an integer with a specific bit depth, you use Int8, Int16, Int32, or Int64.

There are also unsigned variants of the Int types. You can prefix the Int type name with a U to get the corresponding unsigned version: UInt8, UInt16, UInt32, or UInt64.

Because Swift is a strongly typed language, you can’t mix and match these Int types haphazardly. You cannot even do basic math or comparisons with mixed types. In Objective-C it’s common to see NSUInteger values assigned to or compared with an NSInteger, with little regard for a possible overflow. This is especially common when using the count property on an NSArray variable:

for (NSInteger i = 0; i < [someNSArray count]; ++i) {
    NSLog(@"%@", someNSArray[i]);

Since NSArray’s count method actually returns an NSUInteger value, this example compares two different types. It even passes in the wrong type to the array’s subscript. This is a bug just waiting to go BOOM!—most likely after you’ve shipped the app, and a user has more data than you imagined or tested with, thus hitting an overflow.

This sort of bug just can’t happen with Swift. The compiler won’t let you mix unsigned and signed values, and it won’t let you mix variables with different bit depths. Nor will it let you assign one type to another. For this reason, Apple recommends that you always use the Int type unless you specifically need a certain bit depth or have to use an unsigned value (perhaps for really large numbers). This helps you avoid having to convert one Int type to another. Apple has modified the Cocoa classes to follow this guideline. As mentioned earlier in this chapter, in Objective-C, NSArray’s count property returns an NSUInteger (unsigned), but in Swift it returns an Int (signed), even though it can never be negative.

In cases in which you need to convert from one type to another, you can do so by creating a new instance of the destination type, using the original value as its initial value:

var a32BitInt: Int32 = 10
var a64BitInt: Int64 = Int64(a32BitInt)
//a64BitInt: 10 (in a 64-bit variable)

This works by creating a new Int64 with an initial value of a32BitInt.

Be careful, however, because this can create overflow situations. The compiler will catch obvious overflows for you, but it cannot catch all instances, like this:

var a64BitInt: Int64 = Int64.max
var a32BitInt: Int32 = Int32(a64BitInt)
//error: a32BitInt overflows

1.2.2 Double and Float

When you need to work with decimal numbers in Swift, you can work with Float and Double. Float is always a 32-bit value, while Double is always a 64-bit value, regardless of the device architecture.

When using decimal literal values, the compiler always infers a Double type and not a Float. Therefore, if you don’t need the precision of a 64-bit value, you should explicitly declare the variable as a Float, like this:

var distance = 0.0
//distance is a Double
var seconds: Float = 0.0
//seconds is a Float

The following examples show some useful properties. These examples use a Float, but they would work just the same with a Double:

var someFloat = Float.NaN
if someFloat.isNaN {
    println("someFloat is not a number")

someFloat = Float.infinity
if someFloat.isInfinite {
    println("someFloat is equal to infinity")

someFloat = -Float.infinity
if someFloat.isInfinite {
    println("someFloat is equal to infinity,")
    println("even though it's really negative infinity")

if someFloat.isInfinite && someFloat.isSignMinus {
    println("someFloat is equal to negative infinity")

someFloat = 0/0
if someFloat.isNaN {
    println("someFloat is not a number")
    println("note, we divided by zero and did not crash!")

1.2.3 Bool

The Bool type stores Boolean values and is very similar to what you’re used to in Objective-C. However, Swift uses true and false rather than Objective-C’s YES and NO.

In Objective-C, pretty much anything can be converted to a Boolean. If it is something, it’s treated as YES, and if it is nothing (e.g., nil), it’s NO. Here’s an example:

NSInteger someInteger = 0;
BOOL hasSome = someInteger;
//hasSome: NO
someInteger = 100;
hasSome = someInteger;
//hasSome: YES
NSObject* someObject = nil;
BOOL isValidObject = someObject;
//isValidObject: NO

This is not the case with Swift. With Swift, only expressions that explicitly return a Bool may be used to define a Bool value. You can’t implicitly compare values to 0 or nil. Here’s an example:

var someInteger = 0
var hasSome:Bool = (someInteger != 0)
//hasSome: false
someInteger = 100
hasSome = (someInteger != 0)
//hasSome = true

1.2.4 Strings

Strings in Swift are very different from strings in Objective-C. In Swift, String literals are simply text surrounded by double quotes:

var greetingString = "Hello World"

A String is implemented as a collection of Characters. Each Character represents a Unicode character, one of more than 110,000 characters and symbols from more than 100 scripts. Characters are implemented with one of several character encoding methods, such as UTF-8 or UTF-16. These encoding methods use a variable number of bytes in memory to store each character. Because characters vary in size, you cannot determine the length of a string by looking at its size in memory, as you can in Objective-C. Instead, you must use the countElements() function to determine how many characters are in a String. countElements iterates through the string and looks at each character to determine the count. While Swift’s String is compatible with Objective-C’s NSString, and you can use String wherever NSString is called for, the implementations are different, and thus the element count may not be the same value you would get from the NSString length property. This is because length returns the number of 16-bit code units in the UTF-16 version of the NSString, and some Unicode characters use more than 1. You can use the utf16Count property of a String to access the NSStrings length equivalent:

var myPuppy = "Harlow looks just like this: com01.jpg"
//output: 30
//output: 31, com01.jpg uses 2 16-bit code units

You can concatenate Strings together by using the + operator:

var firstName = "Sabrina"
var lastName = "Wood"
var displayName = firstName + " " + lastName
//displayName: Sabrina Wood

You can also append one string to another by using the += operator:

var name = "Katelyn"
name += " Millington"
//name: Katelyn Millington

Since a String is a collection of Characters, you can iterate through them by using a for-in loop:

var originalMessage = "Secret Message"
var unbreakableCode = ""
for character in originalMessage {
    unbreakableCode = String(character) + unbreakableCode
//unbreakableCode: egasseM terceS

Notice that you cannot concatenate a Character and a String together. You must create a new String that contains the character and concatenate that to the unbreakableCode variable.

The syntax for comparing strings is also much improved in Swift over Objective-C. For example, compare the following Objective-C code:

NSString* enteredPasswordHash = @"someSaltedHash";
NSString* storedPasswordHash = @"someSaltedHash";
BOOL accessGranted = [enteredPasswordHash isEqualToString: storedPasswordHash];
//accessGranted: YES

to this Swift code:

var enteredPasswordHash = "someSaltedHash"
var storedPasswordHash = "someSaltedHash"
var accessGranted = (enteredPasswordHash == storedPasswordHash)
//accessGranted: true

1.2.5 Arrays

Arrays are one of the collection types offered in Swift. An array is an ordered list of items of the same type. In Swift, when you declare an array, you must specify what type it will contain. Once you’ve done that, it can contain only that type. This ensures that when you pull an item out of the array, you’re guaranteed to have the type you expect.

To create an array literal, you surround a list of elements with square brackets, like this:

var dogs = ["Harlow", "Cliff", "Rusty", "Mia", "Bailey"]

Be sure that all elements are of the same type, or you will receive a compile-time error.

There are two ways to indicate the type of an array: the long form and the short form. These two ways are equivalent and can be used interchangeably:

  • Long form: Array<ValueType>
  • Short form: [ValueType]

The syntax to declare and initialize an array using the short form is:

var people: [String] = [] //explicit type
//or, alternately
var people = [String]() //implicit type

This example declares an array variable called people, which will contain String values, and you initialize it to an empty array.

You can use type inference to let the compiler determine the types of objects in the array, provided that you give enough information when you declare it:

let bosses = ["Jeff", "Kyle", "Marcus", "Rob", "Sabrina"]

Because you’re initializing the array with strings, the compiler infers that bosses is an array of type [String].

Given an array variable, there are several key methods you can use to access or modify the contents:

var primaryIds: [Int] = [1, 2, 3]
//primaryIds: [1, 2, 3]
//output: 3
//primaryIds: [1, 2, 3, 4]
primaryIds.insert(5, atIndex:0)
//primaryIds: [5, 1, 2, 3, 4]
//primaryIds: [5, 2, 3, 4]
//primaryIds: [5, 2, 3]
//primaryIds: []
//output: true

You can also use subscripting to access a specific element or range of elements:

var primaryIds: [Int] = [1, 2, 3]
//primaryIds: [1, 2, 3]
//output: 3 (arrays are zero based)
primaryIds[2] = 12
//primaryIds: [1, 2, 12]
primaryIds[0...1] = [10]
//primaryIds: [10, 12]
//notice the [] surrounding the 10
//error: 3 is beyond the bounds (0...2) of the array

Make sure you don’t attempt to access an element that is beyond the bounds of the array, though, or you’ll encounter a run-time error, and your app will crash.

There are some important differences between the Objective-C NSArrays that you’re used to and arrays in Swift. In Objective-C, you can only store objects that are of type NSObject (or a subclass) in an NSArray. This is why classes such as NSNumber exist: They’re object wrappers around basic types so you can use them in collections. You don’t add 3 to an NSArray; you add an NSNumber with a value set to 3 to the array. In Swift, you can add structs, enums, or classes to an array, and because all the base types are implemented as structs, they can all be easily added directly to an array, including literals such as 3. What happens when they are added to the array, however, differs depending on the type that is added. Recall the rules we discussed earlier, about how Swift passes structs compared to how it passes classes. These rules come into play when you’re adding objects to an array. If you add an enum or a struct to an array, you add a copy, not a reference to the original object. If you add a class, however, you add a reference to the object. The same rules apply when you pass an array. The array itself is copied because it is a struct, and then each element is either copied or referenced, depending on whether it is an enum, a struct, or a class.

This means you can alter what elements are in each array independently, without affecting another array. If the elements are enums or structs, you can also alter them independently. If the elements are classes, changing one element will have an effect on the same element in the other array (as well as that object if it exists outside the array).

Here you can see these concepts in action:

var coordA = CGPoint(x: 1, y: 1)
var coordB = CGPoint(x: 2, y: 2)
var coords = [coordA, coordB]
//coordA/B are copied into the coords array
//coords: [{x 1 y 1}, {x 2 y 2}]
var copyOfCoords = coords
//copyOfCoords: [{x 1 y 1}, {x 2 y 2}]
coordA.x = 4
//coordA: {x 4 y 1}
//coords and copyOfCoords are unchanged
//coords: [{x 1 y 1}, {x 2 y 2}]
coords[0].x = 10
//coords: [{x 10 y 1}, {x 2 y 2}]
//copyOfCoords is unchanged, because each element is a struct
//copyOfCoords: [{x 1 y 1}, {x 2 y 2}]

Because arrays are collections, you can iterate over the contents by using a for-in loop:

for coord in coords {
    println("Coord(\(coord.x), \(coord.y))")

You can also use the enumerate() function to access an array index inside the for-in loop:

for (index, coord) in enumerate(coords) {
    println("Coord[\(index)](\(coord.x), \(coord.y))")

1.2.6 Dictionaries

A dictionary is an unordered collection of items of a specific type, each associated with a unique key.

As with arrays, there are two ways to indicate the type of a dictionary: the long form and the short form. These two ways are equivalent and can be used interchangeably:

  • Long form: Dictionary<KeyType, ValueType>
  • Short form: [KeyType: ValueType]

The syntax to declare and initialize a dictionary using the short form is:

var people: [String:SomePersonClass] = [:] //explicit type
//or, alternately
var people = [String:SomePersonClass]() //implicit type

This example declares a dictionary variable called people, which will contain SomePersonClass values associated with String keys, and you initialize it to an empty dictionary.

You can use type inference to let the compiler determine the types of objects in the dictionary when assigning a dictionary literal during the declaration:

var highScores = ["Dave":101, "Aaron":102]

Because you’re initializing the dictionary with keys and values, the compiler infers that the highScores variable is a dictionary of type [String:Int].

You can use any type that conforms to the Hashable protocol as the KeyType value. All of Swift’s basic types are hashable by default, so any of them can be used as a key.

You can access and/or manipulate specific values in a dictionary with subscripting:

//output: Optional(101)
highScores["Sarah"] = 103
//added a new player
//output: Optional(103)
//Don't worry about the Optional() portion of the output.
//We introduce that in Chapter 2, "Diving Deeper into
//Swift's Syntax."

Because a dictionary is a collection, you can iterate through it with a for-in loop:

for (playerName, playerScore) in highScores {
    println("\(playerName): \(playerScore)")

You can determine the number of elements in a dictionary by using the count property. Dictionaries also have two array properties, keys and values, that can be iterated through independently.

  • + 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.


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.


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.


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.


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


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


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.


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.


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