Swift: Basics

Basics — A new programming language for iOS, macOS, watchOS, and tvOS app development.

Additional information

  • provides its own versions of all fundamental C and Objective-C types, including Int for integers, Double and Float for floating-point values, Bool for Boolean values, and String for textual data.
  • Provides powerful versions of the three primary collection types, Array, Set, and Dictionary.
  • Is a type-safe language, which means the language helps you to be clear about the types of values your code can work with.
  • Introduces optional types, which handle the absence of a value.

Constants and Variables

Associate a name with a value of a particular type.

Type Annotations

Var welcomeMessage: String
WelcomeMessage = "Hello"

Additional information

  • To be clear about the kind of values the constant or variable can store.
  • The colon means “…of type…,”.

Printing Constants and Variables

Print(friendlyWelcome)
// Prints "Bonjour!"

Additional information

  • With the print(_:separator:terminator:) function.
  • The print(_:separator:terminator:) function is a global function that prints one or more values to an appropriate output.

Comments

// This is a comment
/* This is also a comment
but is written over multiple lines. */

Additional information

  • To include nonexecutable text in your code, as a note or reminder to yourself.
  • Single-line comments begin with two forward-slashes (//).
  • Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/).

Integers

  • Are either signed (positive, zero, or negative) or unsigned (positive or zero).
  • Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms.
  • These follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32.

Additional information

  • Are whole numbers with no fractional component.

Floating-Point Numbers

Are numbers with a fractional component.

Additional information

  • Can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int.

Type Safety and Type Inference

If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type.

Enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.

Is particularly useful when you declare a constant or variable with an initial value.

Let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int
Let pi = 3.14159
// pi is inferred to be of type Double
Let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

Additional information

  • Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. .
  • Type-checking helps you avoid errors when you’re working with different types of values. .
  • Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.

Numeric Literals

Let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix).

Additional information

  • Numeric literals can contain extra formatting to make them easier to read.
Integer literals can be written as: A decimal number, with no prefix A binary number, with a 0b prefix An octal number, with a 0o prefix A hexadecimal number, with a 0x prefix.

Numeric Type Conversion

Use the Int type for all general-purpose integer constants and variables in your code, even if they’re known to be nonnegative.

Use other integer types only when they’re specifically needed for the task at hand, because of explicitly sized data from an external source, or for performance, memory usage, or other necessary optimization.

Type Aliases

Type Aliases — Define an alternative name for an existing type.

Typealias AudioSample = UInt16
Var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0

Additional information

  • Are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source.

Booleans

Let orangesAreOrange = true
let turnipsAreDelicious = false
If turnipsAreDelicious {
    print("Mmm, tasty turnips!")
} else {
    print("Eww, turnips are horrible.")
}
// Prints "Eww, turnips are horrible."
Let i = 1
if i {
    // this example will not compile, and will report an error
}
Let i = 1
if i == 1 {
    // this example will compile successfully
}

Swift has a basic Boolean type, called Bool.

Additional information

  • Values are referred to as logical, because they can only ever be true or false.
  • Are particularly useful when you work with conditional statements.

Tuples

Are particularly useful as the return values of functions.

Are useful for temporary groups of related values.

Let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
Let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
Let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"
let http200Status = (statusCode: 200, description: "OK")
Print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"

Additional information

  • Group multiple values into a single compound value.
  • The values within a tuple can be of any type and don’t have to be of the same type as each other.
  • You can create tuples from any permutation of types, and they can contain as many different types as you like.

Optionals

Let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"

Use optionals in situations where a value may be absent.

Represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

Error Handling

You use error handling to respond to error conditions your program may encounter during execution.

Allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program.

Func canThrowAnError() throws {
    // this function may or may not throw an error
}
Do {
    try canThrowAnError()
    // no error was thrown
} catch {
    // an error was thrown
}
Func makeASandwich() throws {
    // ...
}

do {
    try makeASandwich()
    eatASandwich()
} catch SandwichError.outOfCleanDishes {
    washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
    buyGroceries(ingredients)
}

Assertions and Preconditions

You use them to make sure an essential condition is satisfied before executing any further code.

You use assertions and preconditions to express the assumptions you make and the expectations you have while coding, so you can include them as part of your code.

Are checks that happen at runtime.

A useful form of documentation within the code.

Swift: Basics — Structure map

Clickable & Draggable!

Swift: Basics — Related pages: