Tradition suggests that the first program in a new language should print the words “Hello,world!” on the screen. In Swift,this can be done in a single line:
print("Hello,world!")
@H_404_6@
If you have written code in C or Objective-C,this Syntax looks familiar to you—in Swift,this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program,so you don’t need amain()
function. You also don’t need to write semicolons at the end of every statement.
This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
NOTE
For the best experience,open this chapter as a playground in Xcode. Playgrounds allow you to edit the code listings and see the result immediately.
Simple Values
Uselet
to make a constant andvar
to make a variable. The value of a constant doesn’t need to be known at compile time,but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
A constant or variable must have the same type as the value you want to assign to it. However,you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above,the compiler infers thatmyVariable
is an integer because its initial value is an integer.
If the initial value doesn’t provide enough information (or if there is no initial value),specify the type by writing it after the variable,separated by a colon.
let implicitInteger = 70
@H_404_6@let implicitDouble = 70.0
@H_404_6@let explicitDouble: Double = 70
@H_404_6@
EXPERIMENT
Create a constant with an explicit type ofFloat
and a value of4
.
Values are never implicitly converted to another type. If you need to convert a value to a different type,explicitly make an instance of the desired type.
let label = "The width is "
@H_404_6@let width = 94
@H_404_6@let widthLabel = label + String(width)
@H_404_6@
EXPERIMENT
Try removing the conversion toString
from the last line. What error do you get?
There’s an even simpler way to include values in strings: Write the value in parentheses,and write a backslash (\
) before the parentheses. For example:
let apples = 3
@H_404_6@let oranges = 5
@H_404_6@let appleSummary = "I have \(apples) apples."
@H_404_6@let fruitSummary = "I have \(apples + oranges) pieces of fruit."
@H_404_6@
EXPERIMENT
Use\()
to include a floating-point calculation in a string and to include someone’s name in a greeting.
Create arrays and dictionaries using brackets ([]
),and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
var shoppingList = ["catfish","water","tulips","blue paint"]
@H_404_6@shoppingList[1] = "bottle of water"
@H_404_6@- @H_404_6@
var occupations = [
@H_404_6@"Malcolm": "Captain",
@H_404_6@"Kaylee": "Mechanic",
@H_404_6@]
@H_404_6@occupations["Jayne"] = "Public Relations"
@H_404_6@
To create an empty array or dictionary,use the initializer Syntax.
If type information can be inferred,you can write an empty array as[]
and an empty dictionary as[:]
—for example,when you set a new value for a variable or pass an argument to a function.
Control Flow
Useif
andswitch
to make conditionals,and usefor
-in
,for
,while
,andrepeat
-while
to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.
let individualscores = [75,43,103,87,12]
@H_404_6@var teamscore = 0
@H_404_6@for score in individualscores {
@H_404_6@if score > 50 {
@H_404_6@teamscore += 3
@H_404_6@} else {
@H_404_6@teamscore += 1
@H_404_6@}
@H_404_6@}
@H_404_6@print(teamscore)
@H_404_6@
In anif
statement,the conditional must be a Boolean expression—this means that code such asif score { ... }
is an error,not an implicit comparison to zero.
You can useif
andlet
together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or containsnil
to indicate that a value is missing. Write a question mark (?
) after the type of a value to mark the value as optional.
var optionalString: String? = "Hello"
@H_404_6@print(optionalString == nil)
@H_404_6@- @H_404_6@
var optionalName: String? = "John Appleseed"
@H_404_6@var greeting = "Hello!"
@H_404_6@if let name = optionalName {
@H_404_6@greeting = "Hello,\(name)"
@H_404_6@}
@H_404_6@
EXPERIMENT
ChangeoptionalName
tonil
. What greeting do you get? Add anelse
clause that sets a different greeting ifoptionalName
isnil
.
If the optional value isnil
,the conditional isfalse
and the code in braces is skipped. Otherwise,the optional value is unwrapped and assigned to the constant afterlet
,which makes the unwrapped value available inside the block of code.
Another way to handle optional values is to provide a default value using the??
operator. If the optional value is missing,the default value is used instead.
let nickName: String? = nil
@H_404_6@let fullName: String = "John Appleseed"
@H_404_6@let informalGreeting = "Hi \(nickName ?? fullName)"
@H_404_6@
Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
let vegetable = "red pepper"
@H_404_6@switch vegetable {
@H_404_6@case "celery":
@H_404_6@print("Add some raisins and make ants on a log.")
@H_404_6@case "cucumber","watercress":
@H_404_6@print("That would make a good tea sandwich.")
@H_404_6@case let x where x.hasSuffix("pepper"):
@H_404_6@print("Is it a spicy \(x)?")
@H_404_6@default:
@H_404_6@print("Everything tastes good in soup.")
@H_404_6@}
@H_404_6@
EXPERIMENT
Try removing the default case. What error do you get?
Notice howlet
can be used in a pattern to assign the value that matched the pattern to a constant.
After executing the code inside the switch case that matched,the program exits from the switch statement. Execution doesn’t continue to the next case,so there is no need to explicitly break out of the switch at the end of each case’s code.
You usefor
-in
to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection,so their keys and values are iterated over in an arbitrary order.
let interestingNumbers = [
@H_404_6@"Prime": [2,3,5,7,11,13],
@H_404_6@"Fibonacci": [1,1,2,8],
@H_404_6@"Square": [1,4,9,16,25],
@H_404_6@]
@H_404_6@var largest = 0
@H_404_6@for (kind,numbers) in interestingNumbers {
@H_404_6@for number in numbers {
@H_404_6@if number > largest {
@H_404_6@largest = number
@H_404_6@}
@H_404_6@}
@H_404_6@}
@H_404_6@print(largest)
@H_404_6@
EXPERIMENT
Add another variable to keep track of which kind of number was the largest,as well as what that largest number was.
Usewhile
to repeat a block of code until a condition changes. The condition of a loop can be at the end instead,ensuring that the loop is run at least once.
var n = 2
@H_404_6@while n < 100 {
@H_404_6@n = n * 2
@H_404_6@}
@H_404_6@print(n)
@H_404_6@- @H_404_6@
var m = 2
@H_404_6@repeat {
@H_404_6@m = m * 2
@H_404_6@} while m < 100
@H_404_6@print(m)
@H_404_6@
You can keep an index in a loop by using..<
to make a range of indexes.
var total = 0
@H_404_6@for i in 0..<4 {
@H_404_6@total += i
@H_404_6@}
@H_404_6@print(total)
@H_404_6@
Use..<
to make a range that omits its upper value,and use...
to make a range that includes both values.
Functions and Closures
Usefunc
to declare a function. Call a function by following its name with a list of arguments in parentheses. Use->
to separate the parameter names and types from the function’s return type.
func greet(person: String,day: String) -> String {
@H_404_6@return "Hello \(person),today is \(day)."
@H_404_6@}
@H_404_6@greet(person: "Bob",day: "Tuesday")
@H_404_6@
EXPERIMENT
Remove theday
parameter. Add a parameter to include today’s lunch special in the greeting.
By default,functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name,or write_
to use no argument label.
func greet(_ person: String,on day: String) -> String {
@H_404_6@return "Hello \(person),today is \(day)."
@H_404_6@}
@H_404_6@greet("John",on: "Wednesday")
@H_404_6@
Use a tuple to make a compound value—for example,to return multiple values from a function. The elements of a tuple can be referred to either by name or by number.
func calculateStatistics(scores: [Int]) -> (min: Int,max: Int,sum: Int) {
@H_404_6@var min = scores[0]
@H_404_6@var max = scores[0]
@H_404_6@var sum = 0
@H_404_6@- @H_404_6@
for score in scores {
@H_404_6@if score > max {
@H_404_6@max = score
@H_404_6@} else if score < min {
@H_404_6@min = score
@H_404_6@}
@H_404_6@sum += score
@H_404_6@}
@H_404_6@- @H_404_6@
return (min,max,sum)
@H_404_6@}
@H_404_6@let statistics = calculateStatistics(scores: [5,100,9])
@H_404_6@print(statistics.sum)
@H_404_6@print(statistics.2)
@H_404_6@
Functions can also take a variable number of arguments,collecting them into an array.
func sumOf(numbers: Int...) -> Int {
@H_404_6@var sum = 0
@H_404_6@for number in numbers {
@H_404_6@sum += number
@H_404_6@}
@H_404_6@return sum
@H_404_6@}
@H_404_6@sumOf()
@H_404_6@sumOf(numbers: 42,597,12)
@H_404_6@
EXPERIMENT
Write a function that calculates the average of its arguments.
Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.
func returnFifteen() -> Int {
@H_404_6@var y = 10
@H_404_6@func add() {
@H_404_6@y += 5
@H_404_6@}
@H_404_6@add()
@H_404_6@return y
@H_404_6@}
@H_404_6@returnFifteen()
@H_404_6@
Functions are a first-class type. This means that a function can return another function as its value.
func makeIncrementer() -> ((Int) -> Int) {
@H_404_6@func addOne(number: Int) -> Int {
@H_404_6@return 1 + number
@H_404_6@}
@H_404_6@return addOne
@H_404_6@}
@H_404_6@var increment = makeIncrementer()
@H_404_6@increment(7)
@H_404_6@
A function can take another function as one of its arguments.
func hasAnyMatches(list: [Int],condition: (Int) -> Bool) -> Bool {
@H_404_6@for item in list {
@H_404_6@if condition(item) {
@H_404_6@return true
@H_404_6@}
@H_404_6@}
@H_404_6@return false
@H_404_6@}
@H_404_6@func lessThanTen(number: Int) -> Bool {
@H_404_6@return number < 10
@H_404_6@}
@H_404_6@var numbers = [20,19,12]
@H_404_6@hasAnyMatches(list: numbers,condition: lessThanTen)
@H_404_6@
Functions are actually a special case of closures: blocks of code that can be called later. The code in a closure has access to things like variables and functions that were available in the scope where the closure was created,even if the closure is in a different scope when it is executed—you saw an example of this already with nested functions. You can write a closure without a name by surrounding code with braces ({}
). Usein
to separate the arguments and return type from the body.
numbers.map({
@H_404_6@(number: Int) -> Int in
@H_404_6@let result = 3 * number
@H_404_6@return result
@H_404_6@})
@H_404_6@
EXPERIMENT
Rewrite the closure to return zero for all odd numbers.
You have several options for writing closures more concisely. When a closure’s type is already known,such as the callback for a delegate,you can omit the type of its parameters,its return type,or both. Single statement closures implicitly return the value of their only statement.
You can refer to parameters by number instead of by name—this approach is especially useful in very short closures. A closure passed as the last argument to a function can appear immediately after the parentheses. When a closure is the only argument to a function,you can omit the parentheses entirely.
Objects and Classes
Useclass
followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration,except that it is in the context of a class. Likewise,method and function declarations are written the same way.
class Shape {
@H_404_6@var numberOfSides = 0
@H_404_6@func simpleDescription() -> String {
@H_404_6@return "A shape with \(numberOfSides) sides."
@H_404_6@}
@H_404_6@}
@H_404_6@
EXPERIMENT
Add a constant property withlet
,and add another method that takes an argument.
Create an instance of a class by putting parentheses after the class name. Use dot Syntax to access the properties and methods of the instance.
var shape = Shape()
@H_404_6@shape.numberOfSides = 7
@H_404_6@var shapeDescription = shape.simpleDescription()
@H_404_6@
This version of theShape
class is missing something important: an initializer to set up the class when an instance is created. Useinit
to create one.
class NamedShape {
@H_404_6@var numberOfSides: Int = 0
@H_404_6@var name: String
@H_404_6@- @H_404_6@
init(name: String) {
@H_404_6@self.name = name
@H_404_6@}
@H_404_6@- @H_404_6@
func simpleDescription() -> String {
@H_404_6@return "A shape with \(numberOfSides) sides."
@H_404_6@}
@H_404_6@}
@H_404_6@
Notice howself
is used to distinguish thename
property from thename
argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as withnumberOfSides
) or in the initializer (as withname
).
Usedeinit
to create a deinitializer if you need to perform some cleanup before the object is deallocated.
Subclasses include their superclass name after their class name,separated by a colon. There is no requirement for classes to subclass any standard root class,so you can include or omit a superclass as needed.
Methods on a subclass that override the superclass’s implementation are marked withoverride
—overriding a method by accident,withoutoverride
,is detected by the compiler as an error. The compiler also detects methods withoverride
that don’t actually override any method in the superclass.
class Square: NamedShape {
@H_404_6@var sideLength: Double
@H_404_6@- @H_404_6@
init(sideLength: Double,name: String) {
@H_404_6@self.sideLength = sideLength
@H_404_6@super.init(name: name)
@H_404_6@numberOfSides = 4
@H_404_6@}
@H_404_6@- @H_404_6@
func area() -> Double {
@H_404_6@return sideLength * sideLength
@H_404_6@}
@H_404_6@- @H_404_6@
override func simpleDescription() -> String {
@H_404_6@return "A square with sides of length \(sideLength)."
@H_404_6@}
@H_404_6@}
@H_404_6@let test = Square(sideLength: 5.2,name: "my test square")
@H_404_6@test.area()
@H_404_6@test.simpleDescription()
@H_404_6@
EXPERIMENT
Make another subclass ofNamedShape
calledCircle
that takes a radius and a name as arguments to its initializer. Implement anarea()
and asimpleDescription()
method on theCircle
class.
In addition to simple properties that are stored,properties can have a getter and a setter.
class EquilateralTriangle: NamedShape {
@H_404_6@var sideLength: Double = 0.0
@H_404_6@- @H_404_6@
init(sideLength: Double,name: String) {
@H_404_6@self.sideLength = sideLength
@H_404_6@super.init(name: name)
@H_404_6@numberOfSides = 3
@H_404_6@}
@H_404_6@- @H_404_6@
var perimeter: Double {
@H_404_6@get {
@H_404_6@return 3.0 * sideLength
@H_404_6@}
@H_404_6@set {
@H_404_6@sideLength = newValue / 3.0
@H_404_6@}
@H_404_6@}
@H_404_6@- @H_404_6@
override func simpleDescription() -> String {
@H_404_6@return "An equilateral triangle with sides of length \(sideLength)."
@H_404_6@}
@H_404_6@}
@H_404_6@var triangle = EquilateralTriangle(sideLength: 3.1,name: "a triangle")
@H_404_6@print(triangle.perimeter)
@H_404_6@triangle.perimeter = 9.9
@H_404_6@print(triangle.sideLength)
@H_404_6@
In the setter forperimeter
,the new value has the implicit namenewValue
. You can provide an explicit name in parentheses afterset
.
Notice that the initializer for theEquilateralTriangle
class has three different steps:
-
Setting the value of properties that the subclass declares.
@H_404_6@ -
Calling the superclass’s initializer.
@H_404_6@ -
Changing the value of properties defined by the superclass. Any additional setup work that uses methods,getters,or setters can also be done at this point.
@H_404_6@
If you don’t need to compute the property but still need to provide code that is run before and after setting a new value,usewillSet
anddidSet
. The code you provide is run any time the value changes outside of an initializer. For example,the class below ensures that the side length of its triangle is always the same as the side length of its square.
class TriangleAndSquare {
@H_404_6@var triangle: EquilateralTriangle {
@H_404_6@willSet {
@H_404_6@square.sideLength = newValue.sideLength
@H_404_6@}
@H_404_6@}
@H_404_6@var square: Square {
@H_404_6@willSet {
@H_404_6@triangle.sideLength = newValue.sideLength
@H_404_6@}
@H_404_6@}
@H_404_6@init(size: Double,name: String) {
@H_404_6@square = Square(sideLength: size,name: name)
@H_404_6@triangle = EquilateralTriangle(sideLength: size,name: name)
@H_404_6@}
@H_404_6@}
@H_404_6@var triangleAndSquare = TriangleAndSquare(size: 10,name: "another test shape")
@H_404_6@print(triangleAndSquare.square.sideLength)
@H_404_6@print(triangleAndSquare.triangle.sideLength)
@H_404_6@triangleAndSquare.square = Square(sideLength: 50,name: "larger square")
@H_404_6@print(triangleAndSquare.triangle.sideLength)
@H_404_6@
When working with optional values,you can write?
before operations like methods,properties,and subscripting. If the value before the?
isnil
,everything after the?
is ignored and the value of the whole expression isnil
. Otherwise,the optional value is unwrapped,and everything after the?
acts on the unwrapped value. In both cases,the value of the whole expression is an optional value.
let optionalSquare: Square? = Square(sideLength: 2.5,name: "optional square")
@H_404_6@let sideLength = optionalSquare?.sideLength
@H_404_6@
Enumerations and Structures
Useenum
to create an enumeration. Like classes and all other named types,enumerations can have methods associated with them.
enum Rank: Int {
@H_404_6@case ace = 1
@H_404_6@case two,three,four,five,six,seven,eight,nine,ten
@H_404_6@case jack,queen,king
@H_404_6@func simpleDescription() -> String {
@H_404_6@switch self {
@H_404_6@case .ace:
@H_404_6@return "ace"
@H_404_6@case .jack:
@H_404_6@return "jack"
@H_404_6@case .queen:
@H_404_6@return "queen"
@H_404_6@case .king:
@H_404_6@return "king"
@H_404_6@default:
@H_404_6@return String(self.rawValue)
@H_404_6@}
@H_404_6@}
@H_404_6@}
@H_404_6@let ace = Rank.ace
@H_404_6@let aceRawValue = ace.rawValue
@H_404_6@
EXPERIMENT
Write a function that compares twoRank
values by comparing their raw values.
By default,Swift assigns the raw values starting at zero and incrementing by one each time,but you can change this behavior by explicitly specifying values. In the example above,Ace
is explicitly given a raw value of1
,and the rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration. Use therawValue
property to access the raw value of an enumeration case.
Use theinit?(rawValue:)
initializer to make an instance of an enumeration from a raw value.
if let convertedRank = Rank(rawValue: 3) {
@H_404_6@let threeDescription = convertedRank.simpleDescription()
@H_404_6@}
@H_404_6@
The case values of an enumeration are actual values,not just another way of writing their raw values. In fact,in cases where there isn’t a meaningful raw value,you don’t have to provide one.
enum Suit {
@H_404_6@case spades,hearts,diamonds,clubs
@H_404_6@func simpleDescription() -> String {
@H_404_6@switch self {
@H_404_6@case .spades:
@H_404_6@return "spades"
@H_404_6@case .hearts:
@H_404_6@return "hearts"
@H_404_6@case .diamonds:
@H_404_6@return "diamonds"
@H_404_6@case .clubs:
@H_404_6@return "clubs"
@H_404_6@}
@H_404_6@}
@H_404_6@}
@H_404_6@let hearts = Suit.hearts
@H_404_6@let heartsDescription = hearts.simpleDescription()
@H_404_6@
EXPERIMENT
Add acolor()
method toSuit
that returns “black” for spades and clubs,and returns “red” for hearts and diamonds.
Notice the two ways that thehearts
case of the enumeration is referred to above: When assigning a value to thehearts
constant,the enumeration caseSuit.hearts
is referred to by its full name because the constant doesn’t have an explicit type specified. Inside the switch,the enumeration case is referred to by the abbreviated form.hearts
because the value ofself
is already known to be a suit. You can use the abbreviated form anytime the value’s type is already known.
If an enumeration has raw values,those values are determined as part of the declaration,which means every instance of a particular enumeration case always has the same raw value. Another choice for enumeration cases is to have values associated with the case—these values are determined when you make the instance,and they can be different for each instance of an enumeration case. You can think of the associated values as behaving like stored properties of the enumeration case instance. For example,consider the case of requesting the sunrise and sunset times from a server. The server either responds with the requested information,or it responds with a description of what went wrong.
enum ServerResponse {
@H_404_6@case result(String,String)
@H_404_6@case failure(String)
@H_404_6@}
@H_404_6@- @H_404_6@
let success = ServerResponse.result("6:00 am","8:09 pm")
@H_404_6@let failure = ServerResponse.failure("Out of cheese.")
@H_404_6@- @H_404_6@
switch success {
@H_404_6@case let .result(sunrise,sunset):
@H_404_6@print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
@H_404_6@case let .failure(message):
@H_404_6@print("Failure... \(message)")
@H_404_6@}
@H_404_6@
EXPERIMENT
Add a third case toServerResponse
and to the switch.
Notice how the sunrise and sunset times are extracted from theServerResponse
value as part of matching the value against the switch cases.
Usestruct
to create a structure. Structures support many of the same behaviors as classes,including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code,but classes are passed by reference.
struct Card {
@H_404_6@var rank: Rank
@H_404_6@var suit: Suit
@H_404_6@func simpleDescription() -> String {
@H_404_6@return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
@H_404_6@}
@H_404_6@}
@H_404_6@let threeOfSpades = Card(rank: .three,suit: .spades)
@H_404_6@let threeOfSpadesDescription = threeOfSpades.simpleDescription()
@H_404_6@
EXPERIMENT
Add a method toCard
that creates a full deck of cards,with one card of each combination of rank and suit.
Protocols and Extensions
Useprotocol
to declare a protocol.
protocol ExampleProtocol {
@H_404_6@var simpleDescription: String { get }
@H_404_6@mutating func adjust()
@H_404_6@}
@H_404_6@
Classes,enumerations,and structs can all adopt protocols.
class SimpleClass: ExampleProtocol {
@H_404_6@var simpleDescription: String = "A very simple class."
@H_404_6@var anotherProperty: Int = 69105
@H_404_6@func adjust() {
@H_404_6@simpleDescription += " Now 100% adjusted."
@H_404_6@}
@H_404_6@}
@H_404_6@var a = SimpleClass()
@H_404_6@a.adjust()
@H_404_6@let aDescription = a.simpleDescription
@H_404_6@- @H_404_6@
struct SimpleStructure: ExampleProtocol {
@H_404_6@var simpleDescription: String = "A simple structure"
@H_404_6@mutating func adjust() {
@H_404_6@simpleDescription += " (adjusted)"
@H_404_6@}
@H_404_6@}
@H_404_6@var b = SimpleStructure()
@H_404_6@b.adjust()
@H_404_6@let bDescription = b.simpleDescription
@H_404_6@
EXPERIMENT
Write an enumeration that conforms to this protocol.
Notice the use of themutating
keyword in the declaration ofSimpleStructure
to mark a method that modifies the structure. The declaration ofSimpleClass
doesn’t need any of its methods marked as mutating because methods on a class can always modify the class.
Useextension
to add functionality to an existing type,such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere,or even to a type that you imported from a library or framework.
extension Int: ExampleProtocol {
@H_404_6@var simpleDescription: String {
@H_404_6@return "The number \(self)"
@H_404_6@}
@H_404_6@mutating func adjust() {
@H_404_6@self += 42
@H_404_6@}
@H_404_6@}
@H_404_6@print(7.simpleDescription)
@H_404_6@
EXPERIMENT
Write an extension for theDouble
type that adds anabsoluteValue
property.
You can use a protocol name just like any other named type—for example,to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type,methods outside the protocol definition are not available.
let protocolValue: ExampleProtocol = a
@H_404_6@print(protocolValue.simpleDescription)
@H_404_6@// print(protocolValue.anotherProperty) // Uncomment to see the error
@H_404_6@
Even though the variableprotocolValue
has a runtime type ofSimpleClass
,the compiler treats it as the given type ofExampleProtocol
. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.
Error Handling
You represent errors using any type that adopts theError
protocol.
enum PrinterError: Error {
@H_404_6@case outOfPaper
@H_404_6@case noToner
@H_404_6@case onFire
@H_404_6@}
@H_404_6@
Usethrow
to throw an error andthrows
to mark a function that can throw an error. If you throw an error in a function,the function returns immediately and the code that called the function handles the error.
func send(job: Int,toPrinter printerName: String) throws -> String {
@H_404_6@if printerName == "Never Has Toner" {
@H_404_6@throw PrinterError.noToner
@H_404_6@}
@H_404_6@return "Job sent"
@H_404_6@}
@H_404_6@
There are several ways to handle errors. One way is to usedo
-catch
. Inside thedo
block,you mark code that can throw an error by writingtry
in front of it. Inside thecatch
block,the error is automatically given the nameerror
unless you give it a different name.
do {
@H_404_6@let printerResponse = try send(job: 1040,toPrinter: "Bi Sheng")
@H_404_6@print(printerResponse)
@H_404_6@} catch {
@H_404_6@print(error)
@H_404_6@}
@H_404_6@
EXPERIMENT
Change the printer name to"Never Has Toner"
,so that thesend(job:toPrinter:)
function throws an error.
You can provide multiplecatch
blocks that handle specific errors. You write a pattern aftercatch
just as you do aftercase
in a switch.
do {
@H_404_6@let printerResponse = try send(job: 1440,toPrinter: "Gutenberg")
@H_404_6@print(printerResponse)
@H_404_6@} catch PrinterError.onFire {
@H_404_6@print("I'll just put this over here,with the rest of the fire.")
@H_404_6@} catch let printerError as PrinterError {
@H_404_6@print("Printer error: \(printerError).")
@H_404_6@} catch {
@H_404_6@print(error)
@H_404_6@}
@H_404_6@
EXPERIMENT
Add code to throw an error inside thedo
block. What kind of error do you need to throw so that the error is handled by the firstcatch
block? What about the second and third blocks?
Another way to handle errors is to usetry?
to convert the result to an optional. If the function throws an error,the specific error is discarded and the result isnil
. Otherwise,the result is an optional containing the value that the function returned.
let printerSuccess = try? send(job: 1884,toPrinter: "Mergenthaler")
@H_404_6@let printerFailure = try? send(job: 1885,toPrinter: "Never Has Toner")
@H_404_6@
Usedefer
to write a block of code that is executed after all other code in the function,just before the function returns. The code is executed regardless of whether the function throws an error. You can usedefer
to write setup and cleanup code next to each other,even though they need to be executed at different times.
var fridgeIsOpen = false
@H_404_6@let fridgeContent = ["milk","eggs","leftovers"]
@H_404_6@- @H_404_6@
func fridgeContains(_ food: String) -> Bool {
@H_404_6@fridgeIsOpen = true
@H_404_6@defer {
@H_404_6@fridgeIsOpen = false
@H_404_6@}
@H_404_6@- @H_404_6@
let result = fridgeContent.contains(food)
@H_404_6@return result
@H_404_6@}
@H_404_6@fridgeContains("banana")
@H_404_6@print(fridgeIsOpen)
@H_404_6@
Generics
Write a name inside angle brackets to make a generic function or type.
func makeArray<Item>(repeating item: Item,numberOfTimes: Int) -> [Item] {
@H_404_6@var result = [Item]()
@H_404_6@for _ in 0..<numberOfTimes {
@H_404_6@result.append(item)
@H_404_6@}
@H_404_6@return result
@H_404_6@}
@H_404_6@makeArray(repeating: "knock",numberOfTimes:4)
@H_404_6@
You can make generic forms of functions and methods,as well as classes,and structures.
// Reimplement the Swift standard library's optional type
@H_404_6@enum OptionalValue<Wrapped> {
@H_404_6@case none
@H_404_6@case some(Wrapped)
@H_404_6@}
@H_404_6@var possibleInteger: OptionalValue<Int> = .none
@H_404_6@possibleInteger = .some(100)
@H_404_6@
Usewhere
right before the body to specify a list of requirements—for example,to require the type to implement a protocol,to require two types to be the same,or to require a class to have a particular superclass.
func anyCommonElements<T: Sequence,U: Sequence>(_ lhs: T,_ rhs: U) -> Bool
@H_404_6@where T.Iterator.Element: Equatable,T.Iterator.Element == U.Iterator.Element {
@H_404_6@for lhsItem in lhs {
@H_404_6@for rhsItem in rhs {
@H_404_6@if lhsItem == rhsItem {
@H_404_6@return true
@H_404_6@}
@H_404_6@}
@H_404_6@}
@H_404_6@return false
@H_404_6@}
@H_404_6@anyCommonElements([1,3],[3])
@H_404_6@
EXPERIMENT
Modify theanyCommonElements(_:_:)
function to make a function that returns an array of the elements that any two sequences have in common.
Writing<T: Equatable>
is the same as writing<T> ... where T: Equatable
.