Chapter 1. Introduction to Swift

Swift features covered in this chapter:

  • Language features - we introduce the Swift language, creating a foundation that will help you throughout the book.
  • Syntax of Swift - we provide a basic reference of the Swift syntax.

Swift is cool

Swift is the coolest thing since sliced bread. Seriously. Swift represents the next big iteration in the evolution of application development and it has been greeted with open arms by developers around the globe. As the successor to Objective-C—a language that despite it’s merits, had a steep learning curve—Swift has a very sustainable and vibrant future in the development community.

Designed with modern languages in mind, Swift feels familiar to a wide range of developers with its likeness to Python, Ruby, JavaScript and Scala. While it looks and feels similar to a scripting language, Swift actually packs the power, performance and rigidity that are typically found in low level languages. You may still find yourself dabbling with many older low-level languages such as C++ or Objective-C, but you will find that Swift makes it incredibly easy to integrate and operate with many of these languages. Additionally, the future of language integration will likely continue to improve as engineers release updates to the Swift language and compiler.

Consider some of the attributes that make for a great language: community, features and ease-of-use. Swift has embraced many aspects of other languages to harness a blend of these best language attributes.

Features of the language

Swift is a multi-paradigm language that can be used for object-oriented, functional or imperative programming. Swift does not impose a specific paradigm like other languages, but instead offers a spectrum of writing style to developers. It can be used as a purely functional language for one project, and a purely object-oriented language for another project. Swift has some of the best features a programming language can have: closures, static typing, optionals, generics, memory management and interfaces; many of which we will describe in more detail as we go.

Simple and elegant

The Swift standard library (which is essentially the core of the language) is extremely minimal. In all, the language is comprised of less than 100 built-in functions, making the entire language easy to memorize in a very short amount of time.

This leaves Swift with a small amount of reserved keywords in the core language. The following are reserved keywords in Swift that should be avoided when writing code:

class, deinit, enum, extension, func, import, init, internal, let, operator, private, protocol, public, static, struct, subscript, typealias, var, break, case, continue, default, do, else, fallthrough, for, if, in, return, switch, where, while.

These keywords are reserved only in certain context:

associativity, convenience, dynamic, didSet, final, get, infix, inout, lazy, left, mutating, none, nonmutating, optional, override, postfix, precedence, prefix, Protocol, required, right, set, Type, unowned, weak, willSet.

It’s best to avoid these keywords, but if you do feel there is a need to do so you can use them by wrapping the keyword with a back tick:

var `var` = "Some Variable"

The syntax in Swift is also modern, avoiding punctuation where it is unnecessary. For example, semicolon and parenthesis in conditional expressions are optional, but they can be used when desired:

print("Hello "); println("World!")

Minimal but powerful operators

Swift syntax is similar to a C-like language and has a lot of operators that make up a Swift expression.

Assignment operator

You are probably already familiar with this operator, which basically does assignment of the value from the right hand side to the expression on the left hand side as follows:

var someNum = 42

You may or may not be familiar, however, with the other assignment operators that come with Swift. Each of these operators offers convenience and shorthand notation:

*= Multiply and assign
/= Divide and assign
%= Remainder or Modulus and assign
+= Add and assign
-= Subtract and assign
<<= Left bit shift and assign
>>= Right bit shift and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
&&= Logical AND and assign
||= Logical OR and assign

Ternary conditional operator

Like in Java and JavaScript, Swift has a Ternary Operator that quickly allows you to set a value to an expression inline without having to create conditional if else statements. They are written the same way in many other languages.

let value = (price > 1000) ? "High" : "Low"

Type casting operator

Swift has three type casting operator that are isas? and as and use the data from the left hand side, applying the type from the right hand side of the operator.

is is used when you want to figure out whether some data is of a certain type and returns a Boolean value of true or false. For example:

if someVar is String {
  // Do Something
}

as? is a bit similar to is. It checks if the data on the left is of the type on the right, and returns an Optional value, that either contains the variable’s value or contains nil to indicate that the value is missing, which in this case means that it’s not able to typecast the data.

if let newVar = someVar as? String {
   // Sets newVar to someVar if it is possible to typecast
}

as forcefully typecasts the data to the type specified and raises an exception during runtime if it is not possible. It is similar to doing the following:

(someVar as? String)! 

If it is possible to typecast, then it will return the data casted to the type specified.

if let newVar = someVar as String {
  // Sets newVar to someVar if it is possible
  // otherwise throws an exception
}

Type inference, static typing and mutability

Swift uses modern language features like type inference found in Go or Rust to figure out the type of an expression, helping developers avoid typing it out every time.

let someString = "Hello" // someString is set to String type

Like Scala, Swift tries to add an emphasis on immutable variables by using the keyword let, and allows you to create mutable data structures using the keyword var.

let immutableStr = "Some String"
immutableStr += " some text" // Doesn't work

var mutableStr = "Hello World"
mutableStr += "!" // Works

Memory management

Since Swift is developed by Apple, it uses the Automatic Reference Counting (ARC) feature for memory management that is currently used in Objective-C. This helps you focus more on your code rather than on memory management.

Robust data types

Like in every language, Swift has Data Types that are primitives, representing numbers, string, and booleans. It also  has compound types that build on top of the primitives such as arrays, dictionary, functional and tuples. In Swift you have six primary data types:

  1. ​Character
  2. String
  3. Int
  4. Double
  5. Float
  6. Bool

This includes Unicode characters and emojis. A character type can only be created using a literal character within double quotes. A character type is made up of a single character in any language surrounded by quotes.

"ツ"
let puppy: Character = "榱"
let charA = Character("a")

String

A string type is made up of one or more Character types and can be created multiple ways. You can create a string using a literal or by calling the String constructor as such:

let str = "Hello World!"
let newStr = String("From Swift")

Integer

An Int type is a numeric type that is a whole number without any decimal point or fraction like 42 and -10. An Int is signed so you can have positive and negative numbers, but it can also be unsigned. Unsigned integers have a type of UInt.

Swift also provides Int of different sizes such as 8, 16, 32 and 64 bits, which can be signed and unsigned. Their types are defined by appending the bit size after the type:

Int64 or UInt32

Double

A double type is a numeric type with fractions such as 3.1415 or -123.88. A double is 64 bit in size and is used when representing very large numbers or numbers with precision.

Float

A float type is just like double type but is 32 bit in size and can be used when 64 bit precision is not needed like in a double type.

Boolean

Bool is a logical data type that holds a truth value. It can take the value of only true or false.

There are also nine more complex data types, which allow you to store multiple values, do multiple assignments, create interfaces and much more. These nine types are known as compound data types and they consist of:

  1. Array
  2. Dictionary
  3. Function
  4. Type Identified
  5. Tuple
  6. Optional
  7. Implicitly Unwrapped Optional
  8. Protocol Composition
  9. Metatype

Array

The Array type is a compound data type that stores multiple values of the same data type. It is ordered and each item in the array does not have to be uniq. An array can be created multiple ways using the square bracket notation or calling the constructor.

let array = [Int]()
let anotherArray = Array<Int>()
let yetAnotherArray: [Int] = []
let cars = ["Audi", "BMW", "Chevy"]

You can access or set values on an array using subscript notation:

let car = nums[1] // "BMW"

Dictionary

Dictionary type is another compound type similar to Hash or Map in other languages. It stores a value given a key. The keys must be of the same type and must be a descendent of the Hashable type. All of the values also must be of the same type, but unlike the keys, they do not have to implement as Hashable. A dictionary can be created using a literal or calling the constructor.

let dict = Dictionary<String, Int>
let anotherDict = [String: Int]()
let carsToRating = ["Audi": 10, "BMW": 8]

Function

Function is a compound type that represents a type of function or a closure that is an anonymous function. It has an input parameter type and return type:

(String) -> (Bool)

In this example the input parameter type is String and the return type is Bool, but since the parameter type can be any type you can have a function as a parameter type of a function and even return a function inside of a function.

Tuple

Tuple is another compound type that consists of zero or more data types enclosed in parenthesis. Tuples come in handy when you want to return multiple values from a function as a function can only return one data type. To create an empty tuple you can use the keyword Void, which is an alias for ().

Optionals

Swift provides safety features, such as having an Optional type like in Scala that will help you avoid a whole range of bugs due to null pointers. It features Generics, like in Java, allowing code to be more reusable across different data types. Swift also treats functions as first class citizens, like in JavaScript, and has a REPL (Read-Eval-Print-Loop) for debugging. REPL of course exists in interpreted languages like Ruby and Python.

let foundNum = find([1, 2, 3], 8)
foundNum
=> Int? = nil

Optionals are a wrapper data type that wrap an underlying datatype to provide safety in Swift code. Optional was introduced to let you know that the value of a variable can be nil and extra care needs to be taken before using it. You can create an optional using the question mark after the data type when declaring a variable or by using the optional constructor.

let someVar: Int?
let otherVar = Optional<Int>()
let varWithValue = Optional<Int>(88)

Instead of having a notion of -1, nil, NULL or zero to represent nothing or null, Swift provides an Optional to let you know that the value can be nil and that extra safety needs to be taken when handling it. Optional is no more than a wrapper, but it can be unwrapped as follows:

let unwrappedNum = find([1, 2, 3], 2)!

// OR
if let someNum = find([1, 2, 3], 2) {
  // Go here if find returns a value other than nil
}

// OR call a method without using if condition
find([1, 2, 3], 8)?.description

Keep in mind that in addition to its awesome features, the Swift language has also been introduced to a community of over 2 million developers, many of which are converting to Swift as their primary language. Many of the tools, frameworks, libraries and other assets that previously existed in the Objective-C ecosystem are already compatible with Swift, or are even being rewritten to take advantage of Swift-specific features. This also means that the developers that previously supported the Objective-C ecosystem are likely to be active in Swift community discussions, IRC and forums.

In this book we will dive into the core of Swift and show you how expressive and fun the Swift language is. You will quickly admire its plain-English syntax, its versatility and its flexibility. By the end of the book, you will have learned the majority of the Swift programming language and you will feel comfortable and familiar working with Cocoa API’s, leaving you with the tools and understanding necessary to tackle applications of any nature or size.

Why develop games in Swift?

As a game developer it is important to use a language that has a high degree of support for game development, as well as long term sustainability. Swift is one such language. With the support of Apple as an organization, maintaining and promoting the language, Swift will be pushed passionately into the development community. Apple also maintains and updates the Cocoa libraries, which further enhance and ease game development with frameworks such as Sprite Kit and Scene Kit; two very complete frameworks for use in respectively 2D and 3D game development. Games developed in Swift will also run on Apple’s iOS devices, which include the iPhone, iPad and iPod, and quite possibly many future devices Apple may release.

For all of these reasons, our approach in this book is to teach you Swift while developing a cool and casual 2D game called Pencil Adventure. By the time you finish the book, you will be ready to create your own games using Swift.

You can read the full source code of our Pencil Adventure game here on Github.

Integrated Development Environment

While Swift alone is a great language and tool for game development, there are many additional advantages in the Integrated Development Environment (IDE) software that accompanies Swift. Xcode, Simulator, Instruments and Interface Builder comprise an entire suite that will foster your development, testing, profiling and designing respectively.

Xcode editor

Xcode is a free IDE editor that can be downloaded through the Mac App Store or Apple Developer Center. Think of it as your operating station for all of the other tools. Xcode integrates seamlessly with a multitude of other software for a very unique and linear process for building an application from start to finish.

One of the optional components you can find within Xcode is the command line tools. The command line tools, when installed, allow you to run various commands from Terminal. This gives you advantages when you need to script processes, deployments, or other aspects, but these are more advanced topics that we will dive into later in the book.

In Xcode you can also browse Settings > Downloads and find a few more optional components under Documentation. These documentation sets (or “docsets”) are quite large, so be prepared when downloading them for a few gigs of space to be used. One of the main advantages to having the docs downloaded is offline access and definition lookup when writing code.

An IDE wouldn’t be much without great support for writing code. Xcode provides some incredible features around autocompletion, syntax highlighting and error checking. You can also easily set per-project settings, allowing you to favor 2 space indents instead of 4, for example. The autocompletion integrates with the docs either online or locally, depending on whether you’ve downloaded them. You can jump to definitions of built-in or custom functions within Xcode at any point by holding CMD + click the method you would like to lookup. There is also a symbol navigator that lets you expand the definitions and hierarchy of the Swift language and Cocoa framework.

Interface Builder

Within Xcode is an additional software tool, aptly named Interface Builder, which allows you to drag and drop components into an application. Interface Builder helps you clearly understand what will be displayed to the end user, and helps you tie these components into your code.

Summary

These are the few tools we will use throughout the book, but as far as features go, they are only the tip of the iceberg for Xcode. In upcoming chapters we will also work with and discuss the code repository, profiler tools, and the debugger in Xcode. Now that you’ve had a quick introduction of the tools and language, let’s craft some code!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset