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