Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Gupta Art & Architecture Temple and Sculptures.pptxVirag Sontakke
Ad
Learning Swift 3 Early release 3rd Edition Jonathan Manning
1. Instant Ebook Access, One Click Away – Begin at ebookgate.com
Learning Swift 3 Early release 3rd Edition
Jonathan Manning
https://ebookgate.com/product/learning-swift-3-early-
release-3rd-edition-jonathan-manning/
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Click here to visit ebookgate.com and download ebook now
2. Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Learning Puppet 4 1 (Early Release) Edition Jo Rhett
https://ebookgate.com/product/learning-puppet-4-1-early-release-
edition-jo-rhett/
ebookgate.com
Beginning Xcode Swift 3 Edition Edition Knott
https://ebookgate.com/product/beginning-xcode-swift-3-edition-edition-
knott/
ebookgate.com
Gulliver s Travels Webster s German Thesaurus Edition
Jonathan Swift
https://ebookgate.com/product/gulliver-s-travels-webster-s-german-
thesaurus-edition-jonathan-swift/
ebookgate.com
iOS Swift Game Development Cookbook 2nd Edition Simple
Solutions for Game Development Problems Jonathon Manning
https://ebookgate.com/product/ios-swift-game-development-cookbook-2nd-
edition-simple-solutions-for-game-development-problems-jonathon-
manning/
ebookgate.com
3. Learning Virtual Reality Developing Immersive Experiences
and Applications for Desktop Web and Mobile 1 (Early
Release) Edition Tony Parisi
https://ebookgate.com/product/learning-virtual-reality-developing-
immersive-experiences-and-applications-for-desktop-web-and-
mobile-1-early-release-edition-tony-parisi/
ebookgate.com
C in a Nutshell 2 (Early Release) Edition Peter Prinz
https://ebookgate.com/product/c-in-a-nutshell-2-early-release-edition-
peter-prinz/
ebookgate.com
HBase The Definitive Guide 2 (Early Release) Edition Lars
George
https://ebookgate.com/product/hbase-the-definitive-guide-2-early-
release-edition-lars-george/
ebookgate.com
Electronic and Computer Music 3rd Edition Peter Manning
https://ebookgate.com/product/electronic-and-computer-music-3rd-
edition-peter-manning/
ebookgate.com
Machine Learning Algorithms in Depth Final Release 1st
Edition Vadim Smolyakov
https://ebookgate.com/product/machine-learning-algorithms-in-depth-
final-release-1st-edition-vadim-smolyakov/
ebookgate.com
7. Jon Manning, Paris Buttfield-Addison, and Tim Nugent
Learning Swift 3
Boston Farnham Sebastopol Tokyo
Beijing Boston Farnham Sebastopol Tokyo
Beijing
14. Part IV. Extending Your Apps
16. Building a watchOS App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Designing for the Watch 442
Designing Our watchOS App 444
Creating the watchOS Extension 446
Communicating with the iPhone 450
User Interfaces for the Apple Watch 469
Showing Note Contents 475
Creating New Notes 482
Adding Handoff Between the Watch and the iPhone 485
Glances 490
Conclusion 494
17. Code Quality and Distribution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Debugging 495
Instruments 498
Testing 503
Unit Testing 504
UI Testing 506
Using Objective-C and Swift in the Same Project 508
Using Swift Objects in Objective-C 508
Using Objective-C Objects in Swift 509
The App Store 510
App Thinning 511
Testing iOS Apps with TestFlight 512
Conclusion 513
viii | Table of Contents
15. Preface
Welcome to Learning Swift 3! This book will help you put the Swift programming
language into practice by walking you through the development of a note-taking
application for the Apple iOS, OS X, and watchOS platforms.
Swift is a pretty amazing modern language, taking the best from other newer lan‐
guages without reinventing the wheel. Swift is easy to write, easy to read, and really
hard to make mistakes in.
Our philosophy is that the best way to learn Swift is to build apps using it! To build
apps, though, you need a great framework, and Apple has several: Cocoa, Cocoa
Touch, and WatchKit, to name only a few. This book could quite easily be titled
Learning Cocoa and Cocoa Touch with Swift, or something similar, because the frame‐
works are just as important as the language itself. At the time of writing, Swift is cur‐
rently at version 3, and has a bright future ahead of it.
Resources Used in This Book
We recommend following the book by writing code yourself as you progress through
each chapter. If you get stuck, or just want to archive a copy of the code, you can find
what you need via our website.
As this book teaches you how to build a real-world app, we primarily focus on show‐
ing you the coding side of things. We’re not going to ask you to paint your own icons,
so we’ve provided them for you. You can also download them from our website.
Audience and Approach
This book is solely focused on Swift 3 and does not cover the use of Objective-C. We
might mention it occasionally, but we don’t expect you to know how to use it. We first
cover the basics of the Swift 3 language, and then move on to teach as much of the
language as we can, as well as the use of the Cocoa, Cocoa Touch, and watchOS
ix
16. frameworks, through the construction of a complete app for both OS X and iOS. As a
reminder, Swift is the programming language, Cocoa is the framework for OS X apps,
Cocoa Touch is the framework for iOS apps, and somewhat predictably, watchOS is
the framework for the Apple Watch.
This book’s approach differs from that of other programming books that you may
have encountered. As we’ve mentioned, we believe that the best way to learn Swift is
to build apps using it. We assume that you’re a reasonably capable programmer, but
we don’t assume you’ve ever developed for iOS or OS X, or used Swift or Objective-C
before. We also assume that you’re fairly comfortable navigating OS X and iOS as a
user.
Organization of This Book
In this book, we’ll be talking about Cocoa and Cocoa Touch, the frameworks used on
OS X and iOS, respectively. Along the way, we’ll also be covering Swift, including its
syntax and features.
In Part I, Swift Basics, we begin with a look at the tools used for programming with
Swift, as well as the Apple Developer Program. Then we move on to the basics of the
Swift programming language and structuring a program for Apple’s platforms, as well
as common design patterns.
Chapter 1 covers the basics of Apple’s developer program, and guides you through a
simple Swift app.
Chapter 2 explores all the basics of Swift, and prepares you for using it to build more
complex applications.
Chapter 3 discusses Swift’s object-oriented features, as well as the structure of a good
app.
In Part II, An OS X App, we build a simple note-taking application for Macs, target‐
ing OS X. Along the way, we discuss the design of the app, how it’s structured, how it
uses documents, and how to build all the features.
Chapter 4 starts off our OS X notes app, and sets up the document model, and icon.
Chapter 5 goes into detail on working with documents in OS X apps.
Chapter 6 connects the app to iCloud, and finishes up the OS X app.
In Part III, An iOS App, we build a fully featured iOS note-taking application as a
companion for the OS X app from Part II.
Chapter 7 starts off our iOS app, and sets up the same document model for iOS.
Chapter 8 connects the iOS app to iCloud.
x | Preface
17. Chapter 9 creates an interface on iOS for displaying our notes.
Chapter 10 sets up the iOS app to handle attachments.
Chapter 11 adds image support to the iOS app.
Chapter 12 adds sharing and searching support to the iOS app.
Chapter 13 adds a today widget to the iOS app.
Chapter 14 adds location, audio, video, and contact attachments to the iOS app, as
well as notifications.
Chapter 15 finishes the iOS app with a whole lot of polish!
In Part IV, Extending Your Apps, we add a watchOS app, and explore bug hunting
and performance tuning.
Chapter 16 adds a watchOS app to the iOS app, allowing for Apple Watch support.
Chapter 17 explores debugging and performance tuning.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This element signifies a tip or suggestion.
Preface | xi
18. This element signifies a general note.
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, errata, etc.) is available for down‐
load at our website.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples
from O’Reilly books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example code from this book into your product’s documentation does
require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Learning Swift by Jonathon Man‐
ning, Paris Buttfield-Addison, and Tim Nugent (O’Reilly). Copyright 2016 Secret Lab,
978-1-491-94074-7.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at [email protected].
Safari® Books Online
Safari Books Online is an on-demand digital library that deliv‐
ers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
xii | Preface
19. Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/learning-swift.
To comment or ask technical questions about this book, send email to bookques‐
[email protected].
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Jon thanks his mother, father, and the rest of his crazily extended family for their tre‐
mendous support.
Paris thanks his mother, without whom he wouldn’t be doing anything nearly as
interesting, let alone writing books.
Tim thanks his parents and family for putting up with his rather lackluster approach
to life.
Preface | xiii
20. We’d all like to thank our editors, Rachel Roumeliotis and Brian MacDonald—their
skill and advice were invaluable to completing the book. Likewise, all the O’Reilly
Media staff we’ve interacted with over the course of writing the book have been the
absolute gurus of their fields.
A huge thank you to Tony Gray and the Apple University Consortium (AUC) for the
monumental boost they gave us and others listed on this page. We wouldn’t be writ‐
ing this book if it weren’t for them. And now you’re writing books, too, Tony—sorry
about that!
Thanks also to Neal Goldstein, who deserves full credit and/or blame for getting us
into the whole book-writing racket.
We’re thankful for the support of the goons at MacLab (who know who they are and
continue to stand watch for Admiral Dolphin’s inevitable apotheosis), as well as pro‐
fessor Christopher Lueg, Dr. Leonie Ellis, and the rest of the staff at the University of
Tasmania for putting up with us. “Apologies” to Mark Pesce. He knows why.
Additional thanks to Rex S., Nic W., Andrew B., Jess L., and Ash J., for a wide variety
of reasons. And very special thanks to Steve Jobs, without whom this book (and many
others like it) would not have reason to exist.
Thanks also to our tech reviewers, with special thanks to Chris Devers and Tony Gray
for their thoroughness and professionalism.
Finally, thank you very much for buying our book—we appreciate it! And if you have
any feedback, please let us know. You can email us at [email protected] and find us
on Twitter @thesecretlab.
xiv | Preface
23. CHAPTER 1
Getting Started
This book is a work-in-progress. We will be releasing regular Early
Release editions, with a final version late in 2016. The book may be
inconsistent, out of date, or incomplete until then. Please let us
know if you have any feedback by emailing learningswift@secret‐
lab.com.au
This book teaches the Swift 3 programming language by exploring the development
of three applications for Apple platforms: OS X, iOS, and watchOS. This book’s
approach might differ from what you’re used to, because our philosophy is that the
best way to learn Swift is to build apps using it! The vast majority of the code in this
book will be part of the apps we’re building—a full note-taking app for OS X, iOS,
and watchOS—rather than individual pieces of sample code. You can see the final
product in Figure 1-1.
3
24. Figure 1-1. Our finished app, for OS X, iOS, and watchOS
Our app is fully functional, but we do make some deliberate design and feature deci‐
sions along the way to constrain the scope a little (the book is more than 500 pages!).
As we mentioned in the preface, we assume that you’re a reasonably capable pro‐
grammer, but we don’t assume you’ve ever developed for iOS or OS X, or used Swift
or Objective-C before. We also assume that you’re fairly comfortable navigating OS X
and iOS as a user.
We recommend that you work through this book front to back,
building the OS X app, then the iOS app, then the watchOS app,
even if you’re only interested in one of the platforms. By approach‐
ing the book this way, you’ll get the best understanding of what
building a real app with Swift requires.
Programming with Swift, and using the Cocoa and Cocoa Touch frameworks to
develop OS X and iOS apps, respectively, involves using a set of tools developed by
Apple. In this chapter, you’ll learn about these tools, where to get them, how to use
them, how they work together, and what they can do. At the end of this chapter, you’ll
make a very simple Swift application for iOS, before we dive into the details of the
Swift language and Apple’s frameworks in the following two chapters.
4 | Chapter 1: Getting Started
25. The Apple development tools have a long and storied history. Orig‐
inally a set of standalone application tools for the NeXTSTEP OS,
they were eventually adopted by Apple for use as the official OS X
tools. Later, Apple largely consolidated them into one application,
known as Xcode, though some of the applications (such as Instru‐
ments and the iOS simulator) remain somewhat separate, owing to
their relatively peripheral role in the development process. You’ll
notice the prefix NS on many of the classes you use for Cocoa and
Cocoa Touch development with Swift. This prefix comes from the
NeXTSTEP heritage of many of Apple’s frameworks.
In addition to the development tools, Apple offers developers a paid membership in
its Developer Program, which provides resources and support. The program allows
access to online developer forums and specialized technical support for those interes‐
ted in talking to the framework engineers. If you are just interested in learning Swift
and exploring the development tools, you can do so for free. You will need a paid
membership, however, if you wish to use developer services like iCloud in your apps,
or to distribute anything you build through either the iOS or OS X App Store.
Swift is open source, but this doesn’t really mean much when it
comes to using it to develop apps for OS X, iOS, and watchOS.
There’s an excellent community of people working on the language
that you can find at the Swift website.
With the introduction of Apple’s curated App Stores for OS X, iOS, and watchOS, as
well as emerging Apple platforms like tvOS, the Developer Program has become the
official way for developers to provide their credentials when submitting applications
to Apple—in essence, it is your ticket to selling apps through Apple. In this chapter,
you’ll learn how to sign up for the Apple Developer Program, as well as how to use
Xcode, the development tool used to build apps in Swift.
The Apple Developer Program
The paid Apple Developer Program provides access to beta development tools, beta
operating system releases, and distribution ability through Apple’s App Stores. It also
allows you to use some of the cloud-dependent features of the platforms, such as
iCloud, CloudKit, In-App Purchase, Maps, and App Groups.
We will be using a lot of cloud-dependent features, including Maps
and iCloud, in the apps we build throughout this book. You will
not be able to run these apps if you do not have a paid member‐
ship.
The Apple Developer Program | 5
26. It isn’t necessary to be a member of the Apple Developer Program if you don’t intend
to submit apps to the App Stores, or don’t need the cloud-dependent features. We
strongly recommend joining, though, if you intend to build apps for any of Apple’s
platforms, as the other benefits are substantial:
• Access to the Apple Developer Forums, which are frequented by Apple engineers
and designed to allow you to ask questions of your fellow developers and the
people who wrote the OS.
• Access to beta versions of the OS before they are released to the public, which
enables you to test your applications on the next version of the OS X, iOS,
watchOS, and tvOS platforms, and make necessary changes ahead of time. You
also receive beta versions of the development tools.
• A digital signing certificate (one for each platform) used to identify you to the
App Stores. Without this, you cannot submit apps to the App Store, making a
membership mandatory for anyone who wants to release software either for free
or for sale via an App Store.
That said, registering for the Developer Program isn’t necessary to view the docu‐
mentation or to download the current version of the developer tools, so you can play
around with writing apps without opening your wallet.
Registering for the Apple Developer Program
To register for the Developer Program, you’ll first need an Apple ID. It’s quite likely
that you already have one, as the majority of Apple’s online services require one to
identify you. If you’ve ever used iCloud, the iTunes store (for music or apps), or
Apple’s support and repair service, you already have an ID. You might even have
more than one (one of this book’s authors has four). If you don’t yet have an ID, you’ll
create one as part of the registration process. When you register for the Developer
Program, the membership gets added to your Apple ID.
If you don’t want to register for the paid developer program, you
can skip to “Downloading Xcode” on page 7 for instructions on
installing Xcode, the developer tools.
Once again, keep in mind that you won’t be able to build the apps
that we teach in this book if you don’t have a paid membership, as
we use cloud-dependent features such as iCloud and Maps.
There are alternatives to many of Apple’s tools—such as the Google
Maps SDK for iOS, or cloud-storage services from Amazon and
Microsoft. However, you’ll still need a paid membership through
Apple to put apps in the iTunes App Store.
6 | Chapter 1: Getting Started
27. Once you’re on the Apple Developer Program website, simply click Enroll, and follow
the steps to enroll.
You can choose to register as an individual or as a company. If you register as an indi‐
vidual, your apps will be sold under your name. If you register as a company, your
apps will be sold under your company’s legal name. Choose carefully, as it’s very diffi‐
cult to convince Apple to change your program’s type.
If you’re registering as an individual, you’ll just need your credit card. If you’re regis‐
tering as a company, you’ll need your credit card as well as documentation that
proves you have authority to bind your company to Apple’s terms and conditions.
For information on code signing and using Xcode to test and run
your apps on your own physical devices, see Apple’s App Distribu‐
tion Guide. We don’t cover this in the book, as it’s a process that
changes often.
Apple usually takes about 24 hours to activate an account for individuals, and longer
for companies. Once you’ve received confirmation from Apple, you’ll be emailed a
link to activate your account; when that’s done, you’re a full-fledged developer!
Downloading Xcode
To develop apps for either platform, you’ll use Xcode, Apple’s integrated development
environment. Xcode combines a source code editor, debugger, compiler, profiler, iOS
simulator, Apple Watch simulator, and more into one package. It’s where you’ll spend
the majority of your time when developing applications.
At the time of writing, Xcode is only available for Mac, but who
knows what the future holds for the iPad Pro?
You can get Xcode from the Mac App Store. Simply open the App Store application
and search for “Xcode,” and it’ll pop up. It’s a free download, though it’s rather large
(several gigabytes at the time of writing).
Once you’ve downloaded Xcode, it’s straightforward enough to install it. The Mac
App Store gives you an application that on first launch sets up everything you need to
use Xcode. Just launch the downloaded app, and follow the prompts, and you’ll be up
and running in no time.
The Apple Developer Program | 7
28. This book covers Swift 3, which is available only if you’re using
Xcode 7 or later. Make sure you’re using the latest version of Xcode
from the Mac App Store. It’s good practice to use the latest Xcode at
all times.
Creating Your First Project with Xcode
Xcode is designed around a single window. Each of your projects will have one win‐
dow, which adapts to show what you’re working on.
To start exploring Xcode, you’ll first need to create a project by following these steps:
1. Launch Xcode. You can find it by opening Spotlight (by pressing ⌘-space bar)
and typing Xcode. You can also find it by opening the Finder, going to your hard
drive, and opening the Applications directory. If you had any projects open previ‐
ously, Xcode will open them for you. Otherwise, the Welcome to Xcode screen
appears (see Figure 1-2).
Figure 1-2. The Welcome to Xcode screen
2. Create a new project by clicking “Create a new Xcode project” or go to
File→New→Project.
You’ll be asked what kind of application to create. The template selector is divi‐
ded into two areas. On the lefthand side, you’ll find a collection of application
categories. You can choose to create an iOS, watchOS, or OS X application from
the project templates, which will set up a project directory to get you started.
8 | Chapter 1: Getting Started
29. Because we’re just poking around Xcode at the moment, it doesn’t really matter
what we select, so choose Application under the iOS header and select Single
View Application. This creates an empty iOS application and displays the project
settings window shown in Figure 1-3.
Figure 1-3. The project settings window
3. Name the application. Enter HelloSwift in the Product Name section.
4. Enter information about the project. Depending on the kind of project template
you select, you’ll be asked to provide different information about how the new
project should be configured.
At a minimum, you’ll be asked for the following information, no matter which
platform and template you choose:
The product’s name
This is the name of the project and is visible to the user. You can change this
later.
Your organization’s name
This is the name of your company or group. It’s not directly used by Xcode,
but new source code files that you create will mention it.
Creating Your First Project with Xcode | 9
30. Your organization identifier
This is used to generate a bundle ID, a string that looks like a reverse domain
name (e.g., if O’Reilly made an application named MyUsefulApplication, the
bundle ID would be com.oreilly.MyUsefulApplication).
Bundle IDs are the unique identifier for an application,
and are used to identify that app to the system and to the
App Store. Because each bundle ID must be unique, the
same ID can’t be used for more than one application in
either of the iOS or Mac App Stores. That’s why the for‐
mat is based on domain names—if you own the site use‐
fulsoftware.com, all of your bundle IDs would begin with
com.usefulsoftware, and you won’t accidentally use a bun‐
dle ID that someone else is using or wants to use because
nobody else owns the same domain name.
If you don’t have a domain name, enter anything you like, as long as it looks
like a backward domain name (e.g., com.mycompany will work).
If you plan on releasing your app, either to the App Store
or elsewhere, it’s very important to use a company identi‐
fier that matches a domain name you own. The App Store
requires it, and the fact that the operating system uses the
bundle ID that it generates from the company identifier
means that using a domain name that you own eliminates
the possibility of accidentally creating a bundle ID that
conflicts with someone else’s.
If you’re writing an application for the Mac App Store, you’ll also be prompted
for the App Store category (whether it’s a game, an educational app, a social net‐
working app, or something else).
Depending on the template, you may also be asked for other information (e.g.,
the file extension for your documents if you are creating a document-aware
application, such as a Mac app). You’ll also be asked which language you want to
use; because this book is about Swift, you should probably choose Swift! The
additional information needed for this project is covered in the following steps.
5. Make the application run on the iPhone by choosing iPhone from the Devices
drop-down list.
10 | Chapter 1: Getting Started
31. iOS applications can run on the iPad, iPhone, or both. Appli‐
cations that run on both are called “universal” applications and
run the same binary but have different user interfaces. For this
exercise, just choose iPhone. You should be building universal
iOS apps, in general, and we’ll be doing that when we properly
start on iOS, in Part III.
6. Leave the rest of the settings as shown in Figure 1-4. Click Next to create the
project.
Figure 1-4. The project settings
7. Choose where to save the project. Select a location that suits you. We recommend
putting all your work related to this book (and other Swift programming learning
you might do) in one folder. You might notice a little checkbox for Source Con‐
trol; this creates a source code control repository for your code, giving you a
place where you can save and manage different versions of your code as you cre‐
ate them. While in general this is a good idea to use, for this example project,
make sure this is unchecked.
Once you’ve done this, Xcode will open the project, and you can now start using the
entire Xcode interface, as shown in Figure 1-5.
Creating Your First Project with Xcode | 11
32. Figure 1-5. The entire Xcode interface
The Xcode Interface
As mentioned, Xcode shows your entire project in a single window, which is divided
into a number of sections. You can open and close each section at will, depending on
what you want to see.
Let’s take a look at each of these sections and examine what they do.
The editor
The Xcode editor (Figure 1-6) is where you’ll be spending most of your time. All
source code editing, interface design, and project configuration take place in this sec‐
tion of the application, which changes depending on which file you have open.
If you’re editing source code, the editor is a text editor, with code completion, syntax
highlighting, and all the usual features that developers have come to expect from an
integrated development environment. If you’re modifying a user interface, the editor
becomes a visual editor, allowing you to drag around the components of your inter‐
face. Other kinds of files have their own specialized editors as well.
When you first create a project, the editor will start by showing the project settings, as
seen in Figure 1-6.
12 | Chapter 1: Getting Started
33. Figure 1-6. Xcode’s editor, showing the project settings
The editor can also be split into a main editor and an assistant editor through the edi‐
tor selector. The assistant shows files that are related to the file open in the main edi‐
tor. It will continue to show files that have a relationship to whatever is open, even if
you open different files.
For example, if you open an interface file and then open the assistant, the assistant
will, by default, show related code for the interface you’re editing. If you open another
interface file, the assistant will show the code for the newly opened files.
At the top of the editor, you’ll find the jump bar. The jump bar lets you quickly jump
from the content that you’re editing to another piece of related content, such as a file
in the same folder. The jump bar is a fast way to navigate your project.
The toolbar
The Xcode toolbar (Figure 1-7) acts as mission control for the entire interface. It’s the
only part of Xcode that doesn’t significantly change as you develop your applications,
and it serves as the place where you can control what your code is doing.
Figure 1-7. Xcode’s toolbar
From left to right, after the OS X window controls, the toolbar features the following
items:
Run button (Figure 1-8)
Clicking this button instructs Xcode to compile and run the application.
Creating Your First Project with Xcode | 13
34. Figure 1-8. The Run button
Depending on the kind of application you’re running and your currently selected
settings, this button will have different effects:
• If you’re creating a Mac application, the new app will appear in the Dock and
will run on your machine.
• If you’re creating an iOS application, the new app will launch in either the
iOS simulator or on a connected iOS device, such as an iPhone or iPad.
Additionally, if you click and hold this button, you can change it from Run to
another action, such as Test, Profile, or Analyze. The Test action runs any
unit tests that you have set up; the Profile action runs the application Instru‐
ments (we cover this much later, in Chapter 17); and the Analyze action
checks your code and points out potential problems and bugs.
Stop button (Figure 1-9)
Clicking this button stops any task that Xcode is currently doing—if it’s building
your application, it stops; and if your application is running in the debugger, it
quits it.
14 | Chapter 1: Getting Started
35. Figure 1-9. The stop button
Scheme selector (Figure 1-10)
Schemes are what Xcode calls build configurations—that is, what’s being built,
how, and where it will run (i.e., on your computer or on a connected device).
Figure 1-10. The scheme selector
Projects can have multiple apps inside them. When you use the scheme selector,
you choose which app, or target, to build.
To select a target, click on the left hand side of the scheme selector.
You can also choose where the application will run. If you are building a Mac
application, you will almost always want to run the application on your Mac. If
you’re building an iOS application, however, you have the option of running the
application on an iPhone simulator or an iPad simulator. (These are in fact the
same application; it simply changes shape depending on the scheme that you’ve
selected.) You can also choose to run the application on a connected iOS device if
it has been set up for development.
Creating Your First Project with Xcode | 15
36. Status display (Figure 1-11)
The status display shows what Xcode is doing—building your application, down‐
loading documentation, installing an application on an iOS device, and so on.
Figure 1-11. The status display
If there is more than one task in progress, a small button will appear on the left
hand side, which cycles through the current tasks when clicked.
Editor selector (Figure 1-12)
The editor selector determines how the editor is laid out. You can choose to dis‐
play either a single editor, the editor with the assistant, or the versions editor,
which allows you to compare different versions of a file if you’re using a revision
control system like Git or Subversion.
Figure 1-12. The editor selector
We don’t have anywhere near the space needed to talk about
using version control in your projects in this book, but it’s an
important topic. We recommend Jon Loeliger and Matthew
McCullough’s Version Control with Git, 2nd Edition (O’Reilly).
View selector (Figure 1-13)
The view selector controls whether the navigator, debug, and utility panes appear
on screen. If you’re pressed for screen space or simply want less clutter, you can
quickly summon and dismiss these parts of the screen by clicking each of the
elements.
16 | Chapter 1: Getting Started
37. Figure 1-13. The view selector
The navigator
The lefthand side of the Xcode window is the navigator, which presents information
about your project (Figure 1-14).
Figure 1-14. The navigator pane has eight tabs at the top
The navigator is divided into eight tabs, from left to right:
Creating Your First Project with Xcode | 17
38. Project navigator
Lists all the files that make up your project. This is the most commonly used nav‐
igator, as it determines what is shown in the editor. Whatever is selected in the
project navigator is opened in the editor.
Symbol navigator
Lists all the classes and functions that exist in your project. If you’re looking for a
quick summary of a class or want to jump directly to a method in that class, the
symbol navigator is a handy tool.
Search navigator
Allows you to perform searches across your project if you’re looking for specific
text. (The shortcut is ⌘-Shift-F. Press ⌘-F to search the current open document.)
Issue navigator
Lists all the problems that Xcode has noticed in your code. This includes warn‐
ings, compilation errors, and issues that the built-in code analyzer has spotted.
Test navigator
Shows all the unit tests associated with your project. Unit tests used to be an
optional component of Xcode but are now built into Xcode directly. Unit tests are
discussed much later, in “Unit Testing” on page 504.
Debug navigator
Activated when you’re debugging a program, and it allows you to examine the
state of the various threads that make up your program.
Breakpoint navigator
Lists all of the breakpoints that you’ve set for use while debugging.
Report navigator
Lists all the activity that Xcode has done with your project (such as building,
debugging, and analyzing). You can go back and view previous build reports
from earlier in your Xcode session, too.
Utilities
The utilities pane (Figure 1-15) shows additional information related to what you’re
doing in the editor. If you’re editing a Swift source file, for example, the utilities pane
allows you to view and modify settings for that file.
18 | Chapter 1: Getting Started
39. Figure 1-15. The utilities pane, showing information for a source file
Creating Your First Project with Xcode | 19
40. The utilities pane is split into two sections: the inspector, which shows extra details
and settings for the selected item; and the library, which is a collection of items that
you can add to your project. The inspector and the library are most heavily used
when you’re building user interfaces; however, the library also contains a number of
useful items, such as file templates and code snippets, which you can drag and drop
into place.
The debug area
The debug area (Figure 1-16) shows information reported by the debugger when the
program is running. Whenever you want to see what the application is reporting
while running, you can view it in the debug area. By default the debug area is not
shown unless there is a program running. You can bring up the debug area by using
the Xcode Toolbar View selector middle button.
Figure 1-16. The debug area
The area is split into two sections: the left hand side shows the values of local vari‐
ables when the application is paused; the right hand side shows the ongoing log from
the debugger, which includes any logging that comes from the debugged application.
You can show or hide the debug area by clicking on the view selector, at the top right
of the window (see Figure 1-17).
Figure 1-17. The central button in the view selector, which hides and shows the debug
area
Developing a Simple Swift Application
Through the bulk of this book, we’ll be developing a complex, full-fledged Swift
application, spanning three of Apple’s platforms: OS X, iOS, and watchOS. But for
now, before we even explore how and why Swift itself works, we’re going to get a brief
taste by building a very, very simple application for iOS.
20 | Chapter 1: Getting Started
41. If you’re more interested in Mac development, don’t worry! Exactly
the same techniques apply, and we’ll be exploring Mac apps in
detail later on, in Part II.
This simple application is extremely cutting-edge: it will display a single button that,
when tapped, will pop up an alert and change the button’s label to “Test!” We’re going
to build on the project we created earlier in “Creating Your First Project with Xcode”
on page 8, so make sure you have that project open.
It’s generally good practice to create the interface first and then add code. This means
that your code is written with an understanding of how it maps to what the user sees.
To that end, we’ll start by designing the interface for the application.
Designing the Interface
When building an application’s interface using Cocoa and Cocoa Touch, you have
two options. You can either design your application’s screens in a storyboard, which
shows how all the screens link together, or you can design each screen in isolation. As
a general rule, storyboards are a better way to create your interfaces even if you only
have a single view, as in the case of this first application we are building. The reason is
that if you later want to give your application more than one view, it will be easier to
do that in a storyboard.
Start by opening the interface file and adding a button. These are the steps you’ll need
to follow:
1. First, we’ll need to open the main storyboard. Because newly created projects use
storyboards by default, your app’s interface is stored in the Main.storyboard file.
Open it by selecting Main.storyboard in the project navigator. The editor will
change to show the application’s single, blank frame. You may need to pan or
zoom the view around in order to fit it on your monitor.
2. Next, we need to drag in a button. We’re going to add a single button to the
frame. All user interface controls are kept in the Object library, which is at the
bottom of the utilities pane on the right hand side of the screen.
To find the button, you can either scroll through the list until you find Button, or
type button in the search field at the bottom of the library.
Once you’ve located it, drag it into the frame.
3. At this point, we need to configure the button. Every item that you add to an
interface can be configured. For now, we’ll change only the text on the button.
Developing a Simple Swift Application | 21
42. Select the new button by clicking it, and select the Attributes Inspector, which is
the third tab from the right at the top of the utilities pane. You can also reach it
by pressing ⌘-Option-4.
There are many attributes on the button; look for the one labeled Title. The Title
attribute has two different components inside of it, a drop-down box and a text
field containing the text “Button.” In the text field, change the button’s Title to
“Hello!”
You can also change the button’s title by double-clicking it in
the interface.
Our simple interface is now complete (Figure 1-18). The only thing left to do is to
connect it to code.
Figure 1-18. Our completed simple interface
Connecting the Code
Applications aren’t just interfaces—as a developer, you also need to write code. To
work with the interface you’ve designed, you need to create connections between
your code and your interface.
There are two kinds of connections that you can make:
22 | Chapter 1: Getting Started
43. • Outlets are variables that refer to objects in the interface. Using outlets, you can
instruct a button to change color or size, or to hide itself. There are also outlet
collections, which allow you to create an array of outlets and choose which objects
it contains in the interface builder.
• Actions are methods in your code that are run in response to the user interacting
with an object. These interactions include the user touching a finger to an object,
dragging a finger, and so on.
To make the application behave as we’ve just described—tapping the button displays a
label and changes the button’s text—we’ll need to use both an outlet and an action.
The action will run when the button is tapped, and will use the outlet connection to
the button to modify its label.
To create actions and outlets, you need to have both the interface builder and its cor‐
responding code open. Then hold down the Control key and drag from an object in
the interface builder to your code (or to another object in the interface builder, if you
want to make a connection between two objects in your interface).
We’ll now create the necessary connections:
1. First, open the assistant by selecting the second button in the editor selector in
the toolbar. The symbol is two interlocking circles.
The assistant should open and show the corresponding code for the interface
ViewController.swift. If it doesn’t, click the intertwining circles icon (which repre‐
sents the assistant) inside the jump bar and navigate to Automatic→View‐
Controller.swift. Make sure you don’t select the assistant symbol in the toolbar, as
that will close the assistant editor.
2. Create the button’s outlet. Hold down the Control key and drag from the button
into the space below the first { in the code.
A pop-up window will appear. Leave everything as the default, but change the
Name to helloButton. Click Connect.
A new line of code will appear: Xcode has created the connection for you, which
appears in your code as a property in your class:
@IBOutlet weak var helloButton : UIButton
3. Create the button’s action. Hold down the Control key, and again drag from the
button into the space below the line of code we just created. A pop-up window
will again appear.
This time, change the Connection from Outlet to Action, set the Name to showA
lert, and click Connect.
Developing a Simple Swift Application | 23
44. More code will appear. Xcode has created the connection, which is a method
inside the ViewController class:
@IBAction func showAlert(sender: AnyObject) {
}
4. In the showAlert method you just created, add in the new code:
var alert = UIAlertController(title: "Hello!", message: "Hello, world!",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close",
style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
self.helloButton.setTitle("Test!", forState: UIControlState.Normal)
This code does the following things:
It creates a UIAlertController, which displays a message to the user in a
pop-up window. It prepares it by setting its title to “Hello!” and the text
inside the window to “Hello, world!”
Finally, an action that dismisses the alert is added, with the text “Close”.
The alert is then shown to the user.
Finally, it sets the title of the button to “Test!”
The application is now ready to run. Click the Run button in the upper-left cor‐
ner. The application will launch in the iPhone simulator. Don’t worry if the app
takes a while to launch the first time; the simulator can take a fair amount of time
on first launch.
If you happen to have an iPhone or iPad connected to your com‐
puter, Xcode will try to launch the application on the device rather
than in the simulator. To make Xcode use the simulator, go to the
Scheme menu in the upper-left corner of the window and change
the selected scheme to the simulator.
When the app finishes launching in the simulator, tap the button. An alert will
appear; when you close it, you’ll notice that the button’s text has changed.
Using the iOS Simulator
The iOS simulator (Figure 1-19) allows you to test out iOS applications without hav‐
ing to use actual devices. It’s a useful tool, but keep in mind that the simulator behaves
very differently compared to a real device.
24 | Chapter 1: Getting Started
45. Figure 1-19. The iOS simulator
For one thing, the simulator is a lot faster than a real device and has a lot more mem‐
ory. That’s because the simulator makes use of your computer’s resources—if your
Mac has 8 GB of RAM, so will the simulator and if you’re building a processor-
intensive application, it will run much more smoothly on the simulator than on a real
device.
The iOS simulator can simulate many different kinds of devices: everything from the
iPad 2 to the latest iPad Pro, and from the Retina display 3.5- and 4-inch iPhone-
Using the iOS Simulator | 25
46. sized devices to the latest 4.7-inch and 5.5-inch iPhones. It can also test on variable
size devices.
To change the device, open the Hardware menu, choose Device, and select the device
you want to simulate. You can also change which simulator to use via the scheme
selector in Xcode. Each simulator device is unique, and they do not share informa‐
tion. So if you want to test your application on different simulators, you will need to
build it again through Xcode.
If you change hardware in the simulator while running an app, it
will crash and Xcode will alert you. Be wary of changing the hard‐
ware in the simulator while testing applications unless you really
like crashes.
You can also simulate hardware events, such as the home button being pressed or the
iPhone being locked. To simulate pressing the home button, you can either choose
Hardware→Home, or press ⌘-Shift-H. To lock the device, press ⌘-L or choose Hard‐
ware→Lock.
There are a number of additional features in the simulator, which we’ll examine more
closely as they become relevant to the various parts of iOS we’ll be discussing.
Conclusion
In this chapter, we’ve looked at the basics of the Apple Developer Program, as well as
the tools used for building apps. We’ve also made a really quick and simple iOS app,
just to give you a taste of the process. In the next two chapters, we’ll look at the Swift
programming language, using a feature of Xcode and Swift called Playgrounds to
work with Swift code outside of the application context.
26 | Chapter 1: Getting Started
47. CHAPTER 2
The Basics of Swift
This book is a work-in-progress. We will be releasing regular Early
Release editions, with a final version late in 2016. The book may be
inconsistent, out of date, or incomplete until then. Please let us
know if you have any feedback by emailing learningswift@secret‐
lab.com.au
The Swift programming language was first introduced in June 2014 at Apple’s World‐
wide Developers Conference (WWDC). Swift was a surprise to everyone: Apple had
managed to develop an entire language (as well as all of the supporting libraries,
developer tools, and documentation) and make it work seamlessly with the existing
Objective-C language. And on top of that, it was a really good “1.0” language.
In June 2015, Apple announced Swift 2.0, improving the performance of the lan‐
guage, adding a collection of new features, and making the Cocoa and Cocoa Touch
platform APIs more Swift-like in style. Swift was open sourced on December 3, 2015
and is now as much a community run project as it is run by Apple. We can expect
Swift to evolve over time, in line with the developments in the Swift Open Source
project.
Xcode supports having multiple versions of the Swift language
installed. You might have a different version of the language if, for
example, you’ve downloaded a copy of Swift from the open source
project. For information on how to get a copy and use it in Xcode,
go to the Swift project’s Download page.
This book covers Swift 3, which was released in September 13 2016. The 3.0 release
was a very big deal in the Swift community and included numerous changes to the
language as well as to the standard library. With the release of Swift 3 future changes
27
48. to the language aim to be smaller in scope and with greater support of backwards
compatibility in mind.
If you have older Swift code that you need to update to the latest
stable Swift syntax, Xcode provides a converter. Open the Edit
menu and choose Convert→To Latest Swift Syntax… to get started.
Swift draws upon an extensive history of language design and has a number of very
cool design features that make developing software easier, simpler, and safer. We’ll
begin this chapter with a high-level overview of what Swift aims to do, and how it sets
about doing it, before we dive into the details of the language.
As Swift develops, it’s likely that some of the syntax that we use in
this book will become out of date, or change (as is true for any pro‐
gramming book). We’ll keep the book’s page on our site up to date
with a changelog for the latest Swift for as long as we’re able.
In this chapter, you’ll learn the basics of coding in Swift 3.0, which was released in
September 2016.
The Swift Programming Language
The Swift programming language has the following goals:
Safety
Swift is designed to be a safe language. Many of the pitfalls of C, such as acciden‐
tally working with null pointers, are much harder to encounter. Swift is very
strongly typed, and objects aren’t allowed to be null except under very specific
circumstances.
Modernity
Swift contains a large number of modern language features designed to make it
easy to express the logic of your code. These include pattern-matching switch
statements (see “Switches” on page 37), closures (“Closures” on page 56), and the
concept of all values being objects that you can attach properties and functions to
(“Extensions” on page 69).
Power
Swift has access to the entire Objective-C runtime, and is seamlessly bridged to
Objective-C’s classes as well as its own standard library. This means that you can
use Swift right away to write full iOS and OS X apps—you don’t need to wait for
anyone to port any features from Objective-C to Swift. And if you’ve never used
28 | Chapter 2: The Basics of Swift
49. Objective-C, then you don’t need to worry about Objective-C! You can do every‐
thing you need to develop for Apple platforms using Swift.
So, what does Swift look like? Here’s an example:
func sumNumbers(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
let sum = sumNumbers(2,3,4,5)
print(sum)
This code snippet does the following things:
First, a function called sumNumbers is defined. This function takes one or more
Int values, which are integers (whole numbers), and returns a single Int. The
Int... denotes that the function takes a variable number of Int values; you can
access these values through the numbers variable, which is an array.
Inside the function, the variable total is declared. Note that the type isn’t
given—the compiler knows that it stores an Int, because it’s being set to the inte‐
ger value of 0.
Next, a for-in loop starts up, which loops over every number that was sent to the
method. Notice again that the type of the number variable isn’t defined—the com‐
piler infers that, given that numbers is an array of Int values, number should itself
be an Int.
The value of number is added to total.
When the loop is complete, total is returned.
The function sumNumbers is called with a collection of integers, and the result is
stored in the new variable sum. This variable is constant: by defining it with the
let keyword, we tell the compiler that its value never changes. Attempting to
change the value of a constant is an error.
Finally, we display the value using the print function, which prints values out to
the console.
There are a few interesting things to note here:
The Swift Programming Language | 29
51. Gärtner’s work on hybridisation had been preceded by other
enquiries into the same subject, those namely of Knight mentioned
above at the beginning of the century, and Herbert’s more ample
investigations published in his work on Amaryllideae in 1837. Gärtner
did not neglect to compare his observations at all points with the
results of his predecessors, especially those of Koelreuter, and he
deduced from the astonishing mass of material a number of general
propositions respecting the conditions under which the production of
hybrids is possible, the results of crossing, and the causes of failure.
A special interest attaches to his mixed and compound hybrids, to
his experiments on the various degrees of influence which foreign
pollen exercises on the behaviour of the female organ, and the
connection of this point with the formation of varieties. It is
impossible to give a more distinct account of Gärtner’s results
without entering into discussions which would exceed the limits of a
historical survey. It is the less necessary to do so, since Nägeli
undertook in 1865 to give a summary view of all the important
results to be found in the wealth of material supplied by Koelreuter,
Herbert and Gärtner[112]. Gärtner’s experiments in hybridisation
were conducted at Calw in Würtemberg, the place where Koelreuter
had made his in 1762 and 1763. And thus it was in two small cities
of Würtemberg that the foundations of the sexual theory were laid
and the theory itself perfected, as far as it could be by experiment
only, by three of the most eminent among observers. Camerarius in
Tübingen, Koelreuter and K. F. Gärtner in Calw contributed so largely
to the empirical establishment of the theory, that all that was done
by others would seem of small importance, if artificial pollination
only were in question. But Koelreuter was imperfectly acquainted
with the methods by which pollination is usually effected in nature;
Sprengel was the first who saw into all their more important
relations, and the fact must not be concealed, that Gärtner in
regarding Konrad Sprengel’s observations as unworthy of serious
consideration, neglected the most fruitful source of new and
magnificent results. His careful study of the secreting of nectar and
of the sensitiveness of the organs of fertilisation, and his many
52. observations on other biological relations in flowers, would have
found their natural termination, if he had connected them at all
points with Sprengel’s general conclusions respecting the relation of
the structure of the flower to the insect world. This Gärtner entirely
failed to do, and hence in this case also it was reserved for Darwin’s
wonderful talent for combination to sum up the product of the
investigations of a hundred years, and to blend Koelreuter’s,
Knight’s, Herbert’s, and Gärtner’s results with Sprengel’s theory of
flowers into a living whole in such a manner, that now all the
physiological arrangements in the flower have become intelligible
both in their relations to fertilisation, and in their dependence on the
natural conditions under which pollination takes place without the
aid of man. Here, as in morphology and systematic botany, Darwin
found the premisses given and drew the conclusion from them; here
too the certainty of his theory rests on the results of the best
observers, on investigations which find in that theory their necessary
logical and historical consummation.
7. Microscopic investigation into the processes of fertilisation in
the phanerogams; pollen-tube and egg-cells
[113]. 1830-1850.
Those who were convinced of the sexuality of plants had
endeavoured as early as the previous century to form some idea
with the help of the microscope of the way in which the pollen
effects the formation of the embryo in the ovule. We may pass over
Morland’s and Geoffroy’s very rude attempts in this direction:
Needham (1750), Jussieu, Linnaeus, Gleichen, and Hedwig imagined
that the pollen-grain bursts upon the stigma, and that the granules it
contains make their way downwards through the style to the ovules,
and are there either hatched into embryos or assist in their
production. This way of conceiving the matter was closely connected
with the theory of evolution which then prevailed, and seemed to
find some countenance in the seed-corpuscles of animals; it was also
supported by the observation that pollen-grains placed under the
microscope in water often burst and discharge their contents in the
53. form of a granular mucilage. It has been already mentioned that
Koelreuter rejected this view; he declared the bursting of the pollen-
grains to be contrary to nature, and considered the oil which exudes
from the grains to be the fertilising substance. This view was
adopted by Joseph Gärtner and Sprengel, but it fell into disesteem,
while that of Needham and Gleichen commanded some assent some
years longer. The next question was, how the granular contents of
the pollen-grain reach the ovules. Accident supplied a starting-point
for further consideration. Amici, who was examining the hairs on the
stigma of Portulaca for another purpose, saw on that occasion
(1823) the pollen-tube emerge from the pollen-grain, and the
granular contents of the latter, commonly known as the fovilla,
execute streaming movements like the well-known movement in
Chara. The desire to verify this remarkable fact, and to discover how
the fertilising substance is absorbed by the stigma, led Brongniart in
1826 to examine a great number of pollinated stigmas. He
succeeded in establishing the fact that the formation of pollen-tubes
is a very frequent occurrence. The want of perseverance in following
out his observation and a prepossession in favour of Needham’s old
theory prevented him from discovering the course of the pollen-
tubes all the way to the ovules; he supposed, indeed, that after
penetrating into the stigma they open and discharge their granular
contents, and he maintained distinctly that these are analogous to
the spermatozoids in animals, and are the active part of the pollen.
But now Amici addressed himself more earnestly to the question,
and in 1830 he not only followed the pollen-tubes into the ovary, but
also observed that one finds its way into the micropyle of each
ovule.
Thus the question was suddenly brought near to its solution, when
observers began to wander from the right path in different
directions. Robert Brown showed in 1831 and 1833 that the grains in
the pollen-masses of Orchids and Asclepiads put forth pollen-tubes
as in other plants, and that fine tubes are found in the ovary of
Orchids in which pollination has taken place; but he was in doubt
about the connection of these tubes with the pollen-grains, and
54. rather inclined to think that they were formed in the ovary, though
possibly in consequence of the pollination of the stigma. Schleiden
went wrong in a very different way, and by so doing made the
question as prominent in botanical research, as was that of the
origin of cells at this time. He published in 1837 some excellent
investigations into the origin and development of the ovule before
fertilisation, certainly the best and most thorough of the day. He at
the same time showed that Brongniart’s and Brown’s doubts were
unfounded, and confirmed the statement of Amici, that the pollen-
tubes make their way from the stigma to the ovule, which they enter
through the micropyle. But he made them push forward a little too
far, for he asserted positively that ‘the pollen-tube pushes the
membrane of the embryo-sac before it, making an indentation, and
its extremity then appears to lie in the embryo-sac. The extremity of
the tube now swells out into a round or oval shape, and cell-tissue
forms from its contents; the lateral organs, one or two cotyledons,
are then produced, the original apical point remaining more or less
free and forming the plumule. The portion of the tube underneath
the embryo and the fold of the embryo-sac which envelopes it are
divided off sooner or later and disappear, so that the embryo now
really lies in the embryo-sac.’ This view, which appears to rest on
direct observation and is illustrated by figures which answer to the
description, corresponds with the old theory of evolution and has a
striking approximation to the ideas of Morland and Geoffroy; and if it
were correct, it would like these imply the necessity of pollination to
the formation of seeds that should contain embryos, but at the same
time it would do away with that which is the essential point in the
sexuality of plants, for the ovule would merely be the spot adapted
to the hatching of the embryo formed from the pollen. Schleiden’s
idea was at once adopted by Wydler, Gelesnow and various other
botanists, and especially by Schacht, but the most eminent
microscopists withheld their assent. Amici was the first who openly
opposed the new doctrine; before the Italian congress of savants at
Padua in 1842 he endeavoured to prove that the embryo is not
formed at the end of the pollen-tube, but from a portion of the ovule
which was already in existence before fertilisation, and that this part
55. is fertilised by the fluid contained in the pollen-tube. But the choice
of a gourd, a plant eminently unsuitable for his purpose, prevented
his discovering the exact details of the process, and Schleiden did
not hesitate to denounce his assertions in 1845 in the plainest
terms. But in the next year (1846) Amici produced decisive proof for
the views which he had maintained; he showed from the
Orchidaceae, which were peculiarly well adapted for such
investigations, not only that Robert Brown’s doubts above mentioned
were without foundation, but, which is the main point, that a body,
the egg-cell, is present in the embryo-sac of the ovule before the
arrival of the pollen-tube, and that this body is excited by the
presence of the pollen-tube to further development, the formation of
the embryo. He gave a connected account on this occasion for the
first time of the whole course of these processes from the pollination
of the stigma to the perfecting of the embryo.
The correctness of the account given by Amici was confirmed in
the following year by von Mohl and Hofmeister, the latter of whom
described in detail the points which were decisive of the question
from a variety of plants, and illustrated them by very beautiful
figures in a more copious work, ‘Die Enstehung des Embryo der
Phanerogamen,’ Leipzig, 1849. Tulasne also came forward in
opposition to Schleiden’s theory, being thoroughly convinced that
there was no actual contact of the pollen-tube with the egg-cell,
denying indeed the existence of the egg-cell before fertilisation.
Thus a vehement controversy arose on the subject; a prize offered
by the Institute of the Netherlands at Amsterdam was awarded to an
essay of Schacht’s in 1850, which defended Schleiden’s theory, and
illustrated it by a great number of drawings giving incorrect and
indeed inconceivable representations of the decisive points. Von
Mohl says very admirably on this occasion (‘Botanische Zeitung,’
1863, Beilage, p. 7): ‘Now that we know that Schleiden’s doctrine
was an illusion, it is instructive, but at the same time sad, to see
how ready men were to accept the false for the true; some
renouncing all observation of their own dressed up the phantom in
theoretical principles; others with the microscope in hand, but led
56. astray by their preconceptions, believed that they saw what they
could not have seen, and endeavoured to exhibit the correctness of
Schleiden’s notions as raised above all doubt by the aid of hundreds
of figures, which had every thing but truth to recommend them; and
how an academy by rewarding such a work gave fresh confirmation
to an experience which has been repeatedly made good especially in
our own subject during many years past, namely that prize-essays
are little adapted to contribute to the solution of a doubtful question
in science.’ In this case the prize-essay had been refuted before it
appeared by von Mohl, Hofmeister and Tulasne. Schacht adhered all
the more firmly to Schleiden’s theory; after further controversy, in
which other writers of less authority took part, Radlkofer published
in 1856 a complete review of the question, which fully confirmed
Hofmeister’s observations, and gave incidentally an account of
Schleiden’s views in the altered form which they had by that time
assumed; this account showed in fact that Schleiden had completely
retracted his former opinions, and in this retractation Schacht was
soon after compelled to follow him, having become acquainted with
facts observed in the ovule of Gladiolus, which were obviously
irreconcilable with Schleiden’s theory.
Hofmeister had from the first directed special attention to the
questions, whether any bodies are found in the pollen-tube which
answer in any way to spermatozoids, and whether any opening can
be perceived at the end of the tube. He found indeed forms in
Coniferae in 1851, which reminded him of the male organs of
fertilisation in the higher Cryptogams; but the pollen-tube was
closed both in them and in the rest of the Phanerogams, in which
moreover its outer coat attains to a considerable thickness. There
remained therefore only the hypothesis, that a fluid substance
passes through the walls of the pollen-tube and of the embryo-sac
and effects the fertilisation of the egg-cell; thus it was not the theory
of preformation of the last century, to which Brongniart still adhered,
but the view represented by Koelreuter, which ultimately proved to
be nearer the truth, though it may be said that all that remained of
that view was, that the fertilising substance in the Phanerogams is a
57. fluid. The granular contents of the pollen-grains, which were
supposed to be spermatozoids, have since been partly found to be
only innocent starch-grains and drops of oil.
8. Discovery of Sexuality in the Cryptogams.
1837-1860.
By the year 1845 no one capable of forming a judgment on the
question any longer doubted the existence of different sexes in
Phanerogams. But it was not so with the Cryptogams, though a
number of facts were acknowledged at this time which seemed to
point to the conclusion, that a moment arrives sooner or later in the
course of their development also, when a sexual act is accomplished.
But the question had not as yet been systematically studied; no
experimental investigations had been made, or observations of such
a kind as to demonstrate the necessity of sexual union.
The great majority of botanists in the second half of the 18th
century had no longer any doubt that the stamens were organs of
reproduction, and they were anxious to prove the existence of
similar organs in the Cryptogams; they rested in this matter on
external resemblances and analogies, which they interpreted in a
more or less arbitrary manner. The obvious external resemblance
between the antheridia and archegonia in Mosses and the sexual
organs in the Phanerogams led Schmidel and Hedwig to consider
them to be stamens and ovaries, and the conjecture was correct,
though the true nature of the moss-fruit had to be learnt in another
way. Micheli, Linnaeus and Dillen, trusting still more to external
appearance and with slight knowledge of these plants, had before
this taken the fruit for a male flower, and in the case of the rest of
the Cryptogams the best botanists were only feeling their way in the
dark with no certain experience to guide them. It is not necessary to
give a particular account of the views which originated in this way;
one or two may be mentioned by way of example. Koelreuter
regarded the volva of Mushrooms, Gleditsch and Hedwig certain
tube-like cells in their lamellae, as the male organs of fertilisation.
58. Gleichen took the stomata, Koelreuter the indusium, Hedwig even
the glandular hairs of Ferns for anthers. It was not yet suspected
that the course of development and the whole morphology of the
Cryptogams could not be so compared with that of the
Phanerogams; correct and incorrect assumptions with regard to the
sexual organs of the Cryptogams were alike devoid of scientific
value, being mere guesses and vague conjectures. Nor was the state
of things much better even in the first years of the 19th century; and
if by that time a number of occasional observations had been made
which could afterwards be turned to scientific account, these were
as yet only isolated facts without scientific connection, and every
one was at liberty to concede or to refuse sexual organs to the
Cryptogams generally at his own discretion. Meanwhile observations
gradually accumulated, and towards 1845 it began to be possible by
critical examination of them to arrive at something like a clearer
understanding of this part of botany. The majority of botanists
readily accepted Schmidel’s and Hedwig’s opinion with respect to the
Mosses; Vaucher had as early as 1803 maintained that the long-
known conjugation of Spirogyra was a sexual act; Ehrenberg
observed in 1820 the conjugation of a Mould, Syzygites; Bischoff and
Mirbel explained the organisation of the antheridia of the Liverworts
in 1845, while Nees von Esenbeck saw the spermatozoids of
Sphagnum in 1822 and Bischoff those of Chara in 1828, though they
were at first taken for Infusoria, an opinion maintained by Unger as
late as 1834. But it was Unger[114], who in 1837, after careful study
of the spermatozoids of the Mosses in 1837, declared them to be the
male organs of fertilisation; in 1844 Nägeli discovered corresponding
forms on the prothallium of Ferns, which had till then been called a
cotyledon, and in 1846 the spermatozoids of Pilularia, the products
of the small spores which Schleiden had explained to be the pollen-
grains of that plant.
These facts were of the highest importance, but little was to be
made of them as long as the female organ in the plants in question,
the Mosses excepted, was unknown, and meanwhile it was only the
resemblance between vegetable and animal spermatozoids which led
59. to the conjecture, that the one had the same sexual significance as
the other.
Light was suddenly thrown upon the subject, when Count Lesczyc-
Suminsky discovered in 1848 on the supposed cotyledon
(prothallium) of Ferns both the antheridia and the peculiar organs,
inside which the embryo or young fern is formed. Though the
statements respecting the structure and development of these
female organs and of the embryo were inaccurate in some important
points, yet the place was now indicated where it might be presumed
that the fertilisation by the spermatozoids takes place; and as the
history of the germination of the rest of the vascular Cryptogams
was to some extent known through the earlier labours of Vaucher
and Bischoff, the organs of fructification of these plants might now
be sought, where they are really to be found. But an erroneous idea
respecting the meaning of the small spores of the Rhizocarps
propounded by Schleiden had first to be put out of the way, and this
was done by an appeal to the discovery of Nägeli mentioned above
and by the investigations of Mettenius. Then in 1849 Hofmeister
supplied a connected description of the germination of Pilularia and
Salvinia, in which the decisive points as regards the sexual act were
clearly set forth, and the connection of the spermatozoids with the
fertilisation of the egg-cells in the archegonium was established. He
did the same for Selaginella, which is very unlike the Rhizocarps and
Ferns, and in which the spermatozoids are developed from smaller
spores, and fertilise the egg-cells in archegonia formed in the
prothallium of the large spores. By comparing the processes of
germination in these plants with those of Ferns and Mosses, he
succeeded in throwing entirely new light on the whole of the
morphology of these classes of plants, and thus made it possible for
the first time to compare them with one another and with the
Phanerogams, and to form a right estimate of the sexual act in the
Muscineae and Vascular Cryptogams in its relation to the history of
the development of these plants. Hofmeister arrived at the following
conclusion from his observations in 1849: ‘The prothallium in the
vascular Cryptogams is the morphological equivalent of the leaf-
60. bearing Moss-plant, while the leafy plant of a Fern, of a Lycopodium
and a Rhizocarp answers to the capsule of the Moss. In Mosses as in
Ferns there is an interruption of the vegetative development by
sexual procreation, an alternation of generations; this takes place in
the Vascular Cryptogams very soon after germination, in the Mosses
much later.’ The vast importance of this discovery to systematic
botany has been already noticed. The conception of these relations
developed by Hofmeister was not less important to the doctrine of
the sexuality of plants; it swept away at one stroke all the old false
analogies between Phanerogams and Cryptogams and brought to
light the real agreement; Hofmeister had detected in the
archegonium of the Cryptogams the body which is developed there,
as in the ovule of the Phanerogams, into an embryo after
fertilisation, namely the germinal vesicle or egg-cell. Here was the
point of departure for all further systematic comparison in the sexual
propagation of Cryptogams and Phanerogams. All beside was of
secondary importance, even the fact, that the fertilisation of the
egg-cell in the Cryptogams is not effected by a pollen-tube, but by
spermatozoids. It was now easy to show the corresponding relations
of generation in the other cases which Hofmeister had not yet
observed.
Hofmeister’s statements and conclusions respecting Selaginella
and Isoetes were confirmed and some additions made to them by
Mettenius in 1850, and in 1851 appeared Hofmeister’s exhaustive
work ‘Vergleichende Untersuchungen,’ in which the mode of
production of the embryo in Coniferae was represented as an
intermediate form between those of Phanerogams and Cryptogams.
Further contributions were made to the knowledge of the subject;
Henfrey confirmed Hofmeister’s results in the case of Ferns;
Hofmeister himself and Milde observed in 1852 the history of
fertilisation in Equisetaceae, and the former supplied at the same
time a more complete account of the development of Isoetes; in
1855 he described the decisive points in Botrychium and Mettenius
in 1856 those in Ophioglossum.
61. The processes of development before and after fertilisation were
now cleared up by all these discoveries, but the direct observation of
the act of fertilisation was still wanting. Hofmeister (‘Flora,’ 1857, p.
122) describes the state of affairs in the following terms: ‘While
numerous investigations had thrown a clear light on the character of
the male and female organs, and on the way in which the embryo is
formed by repeated division of the egg-cell present before
fertilisation, we continued quite in the dark respecting the particular
nature of the fertilisation. Observation and experiment had
established the fact, that the influence of the spermatozoids on the
archegonia was required to produce an embryo in the latter. Female
moss-plants[115] separated from the male, macrospores in the
Vascular Cryptogams separated from the microspores, had in all
cases proved unproductive; but it was not even certainly known to
what point in the female organ the spermatozoids force their way. It
is true that Lesczyc and after him Mercklin had seen the entry of
moving spermatozoids into the mouth of archegonia in Ferns; but
Lesczyc’s account of the part which he supposed them to play there
afterwards, was proved to be an illusion. I had myself observed
motionless spermatozoids halfway down the neck of archegonia of
an Equisetum; but nothing was to be learnt of the manner in which
the spermatozoid affects the egg-cell. Then it happened that in the
spring of 1851, being engaged in observing the development of the
organs of vegetation of Ferns, I repeatedly saw spermatozoids
moving about in the basilar cells which enclose the egg-cell in the
archegonia of Ferns, and the majority of them even playing about
the egg-cell. Their movements were put an end to during the
observation by the commencement of changes, which the contents
of young vegetable cells which have been cut open usually
experience under the prolonged influence of water.’ Later
observations leave no doubt now that in the Muscineae and Ferns
single spermatozoids force their way into the naked egg-cell of the
archegonium.
The question was first set at rest in the Algae, where the process
of fertilisation could be seen directly and without exposing the
62. objects to destructive influences. That sexual propagation occurs in
the Algae also had seemed probable, since Decaisne and Thuret in
1845 discovered organs in species of Fucus, and Nägeli in 1846 in
Florideae, which scarcely admitted of any other explanation.
Alexander Braun also had called attention to the formation of two
kinds of spores in a large number of fresh-water Algae. But as yet
there was only conjecture. Then Thuret proved by experiment in
1854, that in the genus Fucus the large egg-cells must be fertilised
by very small swarming spermatozoids, in order to set up
germination; both organs can be collected separately and in
numbers in this genus, and be brought together at pleasure; Thuret
even succeeded in obtaining hybrids. Pringsheim first observed in
1855 the formation of spermatozoids in the little horns of Vaucheria
and established the fact that spores capable of germination are not
formed unless the spermatozoids approach the egg-cell. To Thuret’s
statements he added the very important one, that the remains of
spermatozoids may be recognised on the surface of the contents of
the fertilised egg-cell of Fucus, which is already surrounded by a
membrane. About the same time Cohn published his observations on
Sphaeroplea annulina, which confirmed the fact of the approach of
the spermatozoids to the egg-cells, which consequently, as in Fucus
and Vaucheria, form a cell-wall and are rendered capable of further
development.
Still the decisive observation had not yet been made; no one had
yet seen how the two fertilising elements behaved at the moment of
fertilisation. Pringsheim had the good fortune to make this
observation in one of the commonest of fresh water Algae,
Oedogonium. There he saw the moving spermatozoid first come into
contact with the protoplasmatic substance of the egg-cell, and then
force its way into it, blend with it and dissolve. And thus the first
observation was made, which proved decisively that a real
intermixture takes place of the male and female elements of
fertilisation; this important fact was confirmed by De Bary in the
same year.
63. Now that it was once established, that fertilisation in Cryptogams
consists in the blending together of two naked bodies of protoplasm,
the spermatozoid and the egg-cell, it was reasonable to conclude
that conjugation in Spirogyra and generally in Conjugatae, was an
act of fertilisation, only in this case the two fertilisation-elements are
not of different size and shape, but similar in appearance. To this
conclusion De Bary arrived in 1858 in his monograph of the
Conjugatae. This extension of the idea of fertilisation to cases in
which the uniting cells are to outward appearance alike, was of
special value to the theory of sexuality, as was seen in the sequel,
when other forms of fertilisation were observed which made it
necessary still further to extend the idea of sexuality. In 1858
Pringsheim discovered arrangements for fertilisation in another
group of Algae, the Saprolegnieae, which to outward appearance at
least departed widely from those hitherto known in the lower plants.
Thus between the years 1850 and 1860 a number of fundamental
facts were discovered, and were afterwards confirmed and extended
by fresh observations in the course of the following years. It does
not fall within the limits of this work to notice the many discoveries
that were made in this part of botanical science after 1860; we will
only remark, that between 1860 and 1870 the processes of
fructification were observed by Thuret and Bornet in Florideae, and
especially by De Bary and his pupils in Fungi, in some of which very
peculiar forms were brought to light. No doubt any longer exists that
difference of sex prevails generally in the Thallophytes also, though
it is still an open question, whether it may not be wanting in some of
the very simplest and smallest kinds.
One of the most important results of these investigations is
obviously the striking resemblance between many of the processes
of fertilisation in Cryptogams and in the lower animals; here is
another confirmation of the fact, often brought out in other ways by
modern zoological and botanical research, that the points of
resemblance in the vegetable and animal kingdoms appear most
plainly, if we compare together the simplest forms to be found in
64. both; we have in this fact a plain proof also, that both kingdoms
have been developed from like common elements, as the theory of
descent implies. With respect to the true nature of fertilisation itself,
which is evidently a similar process in the main in animals and
plants, we can only say at present, that it amounts in all cases to a
material blending together of the contents of two cells, neither of
which is capable of further development by itself, while the product
of the combination is not only capable of such development, but
unites in itself the characteristics of the two parent forms and
transmits them to its descendants. That fertilisation is not the
intimate union of two bodies possessing a definite form, but that the
male fertilising substance at least may be a simple fluid, appears to
be distinctly shown by the process in Phanerogams; and we may
assume, that in Cryptogams also, the sexual act is not affected by
the form of the fertilisation-elements, though a certain shape and
power of movement is necessary for the conveyance of the fertilising
substance to that which is to be fertilised.
65. CHAPTER II.
History of the Theory of the Nutrition of Plants.
1583-1860.
That plants take up certain substances from their environment for
the purpose of building up their own structures could not be a
matter of doubt even in the earliest times; it was also obvious, that
movements of the nutrient material must be connected with this
proceeding. But it was not so easy to say, what was the nature of
this food of plants, in what manner it finds its way into and is
distributed in them, and what are the forces employed; it was even
for a long time undecided, whether the food taken up from without
suffers any change inside the plant, before it is applied to purposes
of growth. Such were the questions which had engaged the
attention of Aristotle, and which formed the chief subject of
Cesalpino’s physiological meditations.
But the questions respecting the nutrition of plants acquired a
much more definite shape in the latter half of the 17th century,
when the various phenomena of vegetation began to be more
closely observed, and some attempt was made to understand their
relations to the outer world. Malpighi, the founder of phytotomy, was
the first who undertook to explain the share which belongs to the
different organs of the plant in the whole work of nutrition; guided
by analogy, he perceived that the green leaves are the organs which
prepare the food, and that the material so prepared by them passes
into all parts of the plant, there to be stored up or employed for
purposes of growth. But this gave no insight into the nature of the
substances from which plants prepare their food. On this point
Mariotte endeavoured to give such information as could be obtained
from the chemistry of his day; and he has the merit of having
shown, in opposition to the old Aristotelian notion, that plants
convert the food-material which they derive from the ground into
new chemical combinations, while the earth and the water supply
66. the same elements of nutrition to the most different kinds of plants.
It could not escape the notice of physiologists even of that time, that
the water which plants take up from the ground introduces into
them but very small quantities of matter in solution. Van Helmont in
the first half of the 17th century had shown this by an experiment,
the results of which, however, led him to think that plants were able
to produce both the combustible and incombustible parts of their
substance from water. Hales at the beginning of the 18th century
formed a different opinion, being led by the evolution of the gases in
the dry distillation of plants to conclude, that a considerable part of
their substance was absorbed in a gaseous form from the
atmosphere.
The views propounded by Malpighi, Mariotte, and Hales contained
the most important elements of a theory of the nutrition of plants;
fully understood they would have taught that one part of the food of
plants comes from the earth and the water, and another part from
the air; that the leaves change the materials thus obtained in such a
manner as to produce from them the substance of plants and to
apply this to the purposes of growth; but the ideas were not
combined in this way, for during some years after their time
botanists were chiefly engaged in observations on the movement of
the sap in plants, and they arrived even on this point at very obscure
and even contradictory results, because they overlooked the function
of the leaves which had already been recognised by Malpighi. All
insight not only into the chemical processes in the nutrition of
plants, but also into the mechanical laws of the movement of the
sap, and generally into the whole internal economy of plants,
depends on a knowledge of the fact, that it is only the cells which
contain chlorophyll, and therefore in the higher plants the leaves
chiefly as consisting largely of such cells, which have the power of
converting the gaseous food supplied by the atmosphere into the
substance of the plant with the aid of the materials taken up from
the soil. This fact is of fundamental importance to the whole theory
of the nutrition of plants; it is only by a knowledge of it that we can
explain the movement of material connected with nutrition and
67. growth, the dependence of vegetation on light, and to a great extent
also the function of the roots.
But this principle could not be discovered till the new chemical
system founded by Lavoisier took the place of the old phlogistic
chemistry, and it is remarkable that the discoveries, which laid the
foundation of modern chemistry in the period between 1760 and
1780, contributed essentially to the establishment at the same time
of the modern doctrine of the nutrition of plants. Ingen-Houss, in
reliance on Lavoisier’s antiphlogistic views on the composition of air,
water, and the mineral acids, succeeded in proving that all parts of
plants are continually absorbing oxygen and forming carbon dioxide,
but that the green organs at the same time under the influence of
light absorb carbon dioxide and exhale oxygen; and as early as 1796
he considered it probable that plants obtain the whole mass of their
carbon from the carbon dioxide of the atmosphere. Soon after
(1804) de Saussure proved, that plants, while they decompose
carbon dioxide, increase in weight by a greater amount than that of
the carbon which they retain, and that this is to be explained by the
fact that they at the same time fix the elements of water. He likewise
showed that the small quantities of saline compounds, which plants
take up from the soil, are a necessary part of their food, and that it
was at least probable, that the nitrogen of the atmosphere does not
contribute to the formation of nitrogenous substances in plants.
Senebier had before insisted on the fact, that the decomposition of
carbon dioxide under the influence of light only takes place in green
organs.
Thus the most important points in the nutrition of plants were
discovered by Ingen-Houss, Senebier and de Saussure. But, as often
happens in the case of discoveries of such magnitude, their ideas
were for a long time exposed to great misunderstanding. They were
better appreciated in France than in any other country; Dutrochet
and De Candolle were able to see the importance of the interchange
of gases in the green organs to the general nutrition and respiration;
but others, and especially German botanists, were not content with
68. these simple chemical processes as the foundation of the whole
system of nutrition and consequently of the whole life of the plant;
the theory of the vital force, which was elaborated in connection
with the nature-philosophy during the first years of the 19th century,
and was generally accepted by philosophers and physiologists,
chemists and physicists, preferred to supply the plant with a
mysterious substance for its food, which had its source in the life
itself and which it called humus. The most obvious considerations,
which must at once have shown that this humus-theory was absurd,
were entirely overlooked; and thus in the face of de Saussure’s
results the food of plants was once more referred entirely to the soil
and the roots, as it was in the earliest times; one of the
consequences of this humus-theory in combination with the vital
force was that the ash-constituents of plants were supposed to be
merely accidental admixtures or stimulants, or to be directly
produced in the plant by the vital force.
In the period between 1820 and 1840 the reaction set in from
different quarters against the theory of vital force; chemists
succeeded in producing by artificial means certain organic
compounds, which had hitherto been regarded as products of that
force; Dutrochet discovered in endosmose a process, which served
to refer various vital phenomena in plants to physico-mechanical
principles; de Saussure and others showed that the heat of plants is
a product of respiration, and by 1840 the earlier theory of a vital
force might be looked upon as antiquated and obsolete. It remained
to restore to their rights the observations of Ingen-Houss and de
Saussure, which under the influence of that theory and of the
notions respecting the humus had been so utterly misconstrued.
Liebig set aside the humus-theory in 1840, and referred the carbon
of plants entirely to the carbon dioxide of the atmosphere, and their
nitrogenous contents to ammonia and its derivatives; he claimed the
components of the ash as essential factors in the nutrition, and
taking his stand on the general laws of chemistry endeavoured to
obtain chiefly by the method of deduction an insight into the
chemical processes of assimilation and metabolism. The whole
69. theoretical value of the facts discovered by Ingen-Houss, Senebier
and de Saussure was first made apparent by the connection which
Liebig succeeded in establishing between the phenomena of
nutrition. The doctrine of nutrition burst suddenly into new life; firm
ground was gained, and the botanist, no longer distracted by the
difficulties raised by the vital force but resting on physical and
chemical principles, might now resume the task of investigation.
Oxygen-respiration denied by Liebig was first of all re-established by
von Mohl and others. Liebig’s views on the source of nitrogen in
plants and on the importance of the ash-constituents rested chiefly
on general considerations and observations and on calculation, and
had now to be tested by systematic investigation and especially by
experiments on vegetation in individual plants. And here the place of
honour must be assigned to Boussingault, who pursued the path of
pure induction as contrasted with Liebig’s deductive mode of
proceeding, gradually improved the methods for experimenting on
vegetation, and soon succeeded in so producing plants in a purely
mineral soil free from all humus, that he finally settled the question
of the derivation of the carbon from the atmosphere and of the
source of the nitrogen also. He showed from the plants thus
artificially nourished, and with due consideration of the many
sources of error which beset the question, that the uncombined
nitrogen of the atmosphere does not contribute to the nutrition of
plants, but that a normal increase in the nitrogenous substances in a
plant takes place when the roots take up nitrates as well as the
necessary constituents of the ash.
With the exception of some doubts which still remained respecting
the necessity of certain constituents of the ash, such as sodium,
chlorine and silicic acid, the source of the materials which take a part
in the chemistry of the nutrition of plants was known before 1860;
but the knowledge obtained with regard to processes in the interior
of the plant, the origination of organic substances in the processes
of assimilation, and the further changes which they undergo was still
fragmentary and uncertain, and led to no general and conclusive
results.
70. 1. Cesalpino.
Aristotle had sought to determine the nature of the materials
which plants take up as food, and had laid down the proposition,
that the food of all organisms is not simple but composed of various
substances. This view was correct, but he united with it the
erroneous notion, that the food of plants is elaborated beforehand in
the earth, as in a stomach, and is made applicable to purposes of
growth, so as to exclude the necessity of any separation of
excrements in the plant; this error was refuted by Jung, as we shall
see, but nevertheless it continued to live as late as into the 18th
century, and ultimately quite spoilt Du Hamel’s theory of nutrition.
Cesalpino, whom we have learnt to regard as a faithful and gifted
disciple of Aristotle, directed his speculations to the mechanical
rather than to the chemical side of the question, and chiefly tried to
explain the movement of the nutrient sap in plants. He had a larger
stock of material drawn from experience at his disposition than his
master, and it is instructive therefore to make a nearer acquaintance
with his views, because they show how far the old philosophy was in
a condition to turn better empirical knowledge than Aristotle
possessed to a satisfactory use; they will also show that Cesalpino’s
first essays led him to views which can no longer be said to be
strictly Aristotelian.
In the second chapter of the first book of the work from which we
have already quoted, ‘De plantis libri XVI,’ 1583, he raises the
question, in what way the food of plants is taken in and their
nutrition accomplished. In animals we see the food conveyed from
the veins to the heart, which is the laboratory of the warmth of the
body, and after it has been finally perfected there, spread abroad
through the arteries into all parts of the body; and this is effected by
the operation of the force (spiritus) which is generated in the heart
from the food. In plants on the contrary we see no veins, or other
channels, nor do we feel any warmth in them, so that it is difficult to
understand how trees grow to so great a size, since they seem to
71. have much less natural heat than animals. Cesalpino explains this
enigma by saying, that animals require much food for maintaining
the activity of the senses and the movements of their organs. The
larger quantity of animal food also requires larger receptacles,
namely the veins. Plants on the other hand need less food, because
this is only used for purposes of nutrition, or to a very small extent
for the production of internal heat as well, and therefore they grow
more vigorously and bear more fruit than animals. At the same time
plants are not without internal heat, though it cannot be perceived
by the touch because all objects seem cold to us, which are less
warm than our organ of feeling. That plants moreover have veins,
though only narrow ones in accordance with the small mass of their
food, is shown by those which yield a milky juice, such as Euphorbia
and Ficus, which when cut bleed like the flesh of animals; Cesalpino
adds ‘and this is very frequent also in the vine,’ which shows that he
made no distinction between milky juice and the exuding water of
the weeping vine-stock. These narrow veins cannot be seen on
account of their fineness; but in every stem and in every root things
may be discerned which like nerves in animals can be split
longitudinally and are called the nerves of the plant, or also certain
thicker things, such as those which branch in most leaves and are
there called veins. These should be considered as food-passages and
as answering to the veins in animals; but plants have no main vein
like the vena cava in animals, but many fine veins pass from the root
to the heart of the plant (cor, root-neck, see above, Book I. chap. 2),
and ascend from it into the stem; for it was not necessary that the
food should be collected in a common receptacle in plants, as it is in
the heart in animals, where this is necessary for the production of
the spiritus, but it was sufficient that the fluid in plants should be
changed by contact with the medulla cordis (in the root-neck), as it
is changed in animals in the marrow of the brain or in the liver; and
in these organs the veins are very narrow, as they are in plants.
Since plants have no sense-perception, they cannot seek their
food like animals, but they draw up the moisture from the ground
into themselves in a way of their own; but it is not easy to see how
72. this takes place. Cesalpino, in trying to explain this, gives us a
glimpse into the physics of the day, and we observe also to our
surprise an attempt made to explain phenomena in living creatures
by physical laws, a step beyond the limits of Aristotelian modes of
thought and in the right direction. It is not the ratio similitudinis,
which draws iron to the magnet, that can cause the attraction of the
juice by the roots, for then the smaller would be drawn to the larger;
and if the attraction of the fluid of the earth by the roots were the
same thing as the attraction of the iron by the magnet, the moisture
of the earth would draw out the juice from the plant, which is just
what does not happen. Nor can it be the ratio vacui; for since not
moisture only but air also is contained in the earth, the plant would
be filled not with juice but with air. But Cesalpino hits upon a third
kind of cause by which juices may be drawn into the plant. Do not
many dry things, he says, in accordance with their nature attract
moisture, as linen, sponge and powder, while others repel it, as the
feathers of many birds and the herb Adiantum, which are not wetted
even when dipped in water; but the former absorb much water,
because they have more in common with it than with air; of this kind
Cesalpino thinks those parts of plants must be, which the nourishing
soul employs to take in food. Therefore these organs are not
traversed by a continuous canal such as the veins in animals, but
formed like the nerves of a fibrous substance; and thus the power of
suction (bibula natura) conveys the moisture continually to the
place, where the principle of internal heat is placed, just as may be
seen in the flame of a lantern, to which the wick continually
conducts the oil. The absorption of the moisture is also increased by
the outer warmth, for which reason plants grow more vigorously in
spring and summer.
That Cesalpino had no suspicion of the use of the leaves in the
nutrition of plants appears incontestably from his repeating the
Aristotelian idea, that the leaves are only for the protection of young
shoots and fruits from air and sun-light; this idea is no result of
speculation, but came simply from observing a vineyard in a hot
country.
73. 2. First inductive experiments and opening of new points of view in
the History of the Theory of the Nutrition of Plants.
All that Aristotle and his school, Cesalpino not excepted, are able
to tell us about the phenomena of vegetable life, was the result of
the most every-day observations, none of which were critically and
exactly tested to ascertain their actual correctness, while the larger
part of their physiological axioms were not derived from observations
on plants at all, but from philosophical principles, and especially from
analogies taken from the animal world.
The first step towards a scientific treatment of the doctrine of
nutrition was an enlargement and critical examination of the
materials to be gained from experience; nor were any difficult
observations or experiments needed to discover contradictions
between the truths of nature and the old philosophy; all that was
necessary was to look into things more closely and to judge of them
with less prejudice.
In this way Jung was led to oppose one important point of the
Aristotelian account of nutrition. In the second fragment of his work
‘De plantis doxoscopiae physicae minores’ is to be found a remark,
which is evidently directed against the notion that plants receive
their food already elaborated from the earth, and therefore give off
no excrements[116]. Plants, says Jung in accord with Aristotle,
appear not to need a thinking soul (anima intelligente), which would
be able to distinguish wholesome from unwholesome food, and
Aristotle therefore provided them with food which had already been
perfectly prepared in the earth. But Jung takes another view
founded on actual observation. It is very possible, he says, that the
openings in the roots which take in liquid matter are so organised,
that they do not allow every kind of juice to enter, and who can say
that plants have the peculiarity of only absorbing what is useful to
them, for like all other living creatures they have their excreta, which
are exhaled through the leaves, flowers, and fruits. But among these
he reckons the resins and other exuding liquids, and says that it is
74. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com