Immediate Download iOS 12 Programming Fundamentals With Swift Swift Xcode and Cocoa Basics 5th Edition Matt Neuburg Ebooks 2024
Immediate Download iOS 12 Programming Fundamentals With Swift Swift Xcode and Cocoa Basics 5th Edition Matt Neuburg Ebooks 2024
com
https://textbookfull.com/product/ios-12-
programming-fundamentals-with-swift-swift-xcode-
and-cocoa-basics-5th-edition-matt-neuburg-2/
https://textbookfull.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg-2/
textbookfull.com
https://textbookfull.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg-3/
textbookfull.com
https://textbookfull.com/product/ios-10-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg/
textbookfull.com
https://textbookfull.com/product/consuming-utopia-cultural-studies-
and-the-politics-of-reading-1st-edition-storey/
textbookfull.com
Siyasi Muslims: A Story of Political Islams in India Hilal
Ahmed
https://textbookfull.com/product/siyasi-muslims-a-story-of-political-
islams-in-india-hilal-ahmed/
textbookfull.com
https://textbookfull.com/product/stolen-heir-1st-edition-sophie-lark/
textbookfull.com
https://textbookfull.com/product/the-complete-italian-cookbook-
essential-regional-cooking-of-italy-1st-edition-manuela-anelli-
mazzocco/
textbookfull.com
https://textbookfull.com/product/schooling-and-travelling-communities-
dave-cudworth/
textbookfull.com
https://textbookfull.com/product/fundamentals-of-computer-vision-1st-
edition-wesley-e-snyder/
textbookfull.com
Culture Transnational Education and Thinking Case studies
in global schooling 1st Edition Niranjan Casinader
https://textbookfull.com/product/culture-transnational-education-and-
thinking-case-studies-in-global-schooling-1st-edition-niranjan-
casinader/
textbookfull.com
iOS 12 Programming
Fundamentals with Swift
FIFTH EDITION
Swift, Xcode, and Cocoa Basics
Matt Neuburg
iOS 12 Programming Fundamentals with Swift, Fifth Edition
by Matt Neuburg
Copyright © 2018 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com/safari). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com.
Editor: Rachel Roumeliotis
Production Editor: Kristen Brown
Proofreader: O’Reilly Production Services
Indexer: Matt Neuburg
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Matt Neuburg
April 2015: First Edition
October 2015: Second Edition
October 2016: Third Edition
October 2017: Fourth Edition
September 2018: Fifth Edition
Revision History for the Fifth Edition
2018-09-26: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781492044550 for
release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS
12 Programming Fundamentals with Swift, the image of a harp seal,
and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to
ensure that the information and instructions contained in this work
are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for
damages resulting from the use of or reliance on this work. Use of
the information and instructions contained in this work is at your
own risk. If any code samples or other technology this work contains
or describes is subject to open source licenses or the intellectual
property rights of others, it is your responsibility to ensure that your
use thereof complies with such licenses and/or rights.
ISBN: 978-1-492-04455-0
[LSI]
Preface
Safety
Swift enforces strong typing to ensure that it knows, and that
you know, what the type of every object reference is at every
moment.
Economy
Swift is a fairly small language, providing some basic types and
functionalities and no more. The rest must be provided by your
code, or by libraries of code that you use — such as Cocoa.
Memory management
Swift manages memory automatically. You will rarely have to
concern yourself with memory management.
Cocoa compatibility
The Cocoa APIs are written primarily in C and Objective-C. Swift
is explicitly designed to interface with most of the Cocoa APIs.
These features make Swift an excellent language for learning to
program iOS.
The alternative, Objective-C, still exists, and you can use it if you
like. Indeed, it is easy to write an app that includes both Swift code
and Objective-C code; and you may have reason to do so. Objective-
C, however, lacks the very advantages that Swift offers. Objective-C
agglomerates object-oriented features onto C. It is therefore only
partially object-oriented; it has both objects and scalar data types,
and its objects have to be slotted into one particular C data type
(pointers). Its syntax can be difficult and tricky; reading and writing
nested method calls can make one’s eyes glaze over, and it invites
hacky habits such as implicit nil-testing. Its type checking can be
and frequently is turned off, resulting in programmer errors where a
message is sent to the wrong type of object and the program
crashes.
Recent revisions and additions to Objective-C — ARC, synthesis and
autosynthesis, improved literal array and dictionary syntax, blocks —
have made it easier and more convenient, but such patches have
also made the language even larger and possibly even more
confusing. Because Objective-C must encompass C, there are limits
to how far it can be extended and revised. Swift, on the other hand,
is a clean start. If you were to dream of completely revising
Objective-C to create a better Objective-C, Swift might be what you
would dream of. It puts a modern, rational front end between you
and the Cocoa Objective-C APIs.
Still, the reader may also need some awareness of Objective-C
(including C). The Foundation and Cocoa APIs, the built-in
commands with which your code must interact in order to make
anything happen on an iOS device, are still written in C and
Objective-C. In order to interact with them, you might have to know
what those languages would expect.
Therefore, although I do not attempt to teach Objective-C in this
book, I do describe it in enough detail to allow you to read it when
you encounter it in the documentation and on the Internet, and I
occasionally show some Objective-C code. Part III, on Cocoa, is
really all about learning to think the way Objective-C thinks —
because the structure and behavior of the Cocoa APIs are
fundamentally based on Objective-C. And the book ends with an
appendix that details how Swift and Objective-C communicate with
one another, as well as explaining how your app can be written
partly in Swift and partly in Objective-C.
The Scope of This Book
This book is actually one of a pair with my Programming iOS 12,
which picks up exactly where this book leaves off. They complement
and supplement one another. The two-book architecture should, I
believe, render the size and scope of each book tractable for
readers. Together, they provide a complete grounding in the
knowledge needed to begin writing iOS apps; thus, when you do
start writing iOS apps, you’ll have a solid and rigorous understanding
of what you are doing and where you are heading. If writing an iOS
program is like building a house of bricks, this book teaches you
what a brick is and how to handle it, while Programming iOS 12
hands you some actual bricks and tells you how to assemble them.
When you have read this book, you’ll know about Swift, Xcode, and
the underpinnings of the Cocoa framework, and you will be ready to
proceed directly to Programming iOS 12. Conversely, Programming
iOS 12 assumes a knowledge of this book; it begins, like Homer’s
Iliad, in the middle of the story, with the reader jumping with all four
feet into views and view controllers, and with a knowledge of the
language and the Xcode IDE already presupposed. If you started
reading Programming iOS 12 and wondered about such unexplained
matters as Swift language basics, the UIApplicationMain function,
the nib-loading mechanism, Cocoa patterns of delegation and
notification, and retain cycles, wonder no longer — I didn’t explain
them there because I do explain them here.
The three parts of this book teach the underlying basis of all iOS
programming:
Part I introduces the Swift language, from the ground up — I do
not assume that you know any other programming languages. My
way of teaching Swift is different from other treatments, such as
Apple’s; it is systematic and Euclidean, with pedagogical building
blocks piled on one another in what I regard as the most helpful
order. At the same time, I have tried to confine myself to the
essentials. Swift is not a big language, but it has some subtle and
unusual corners. You don’t need to dive deep into all of these,
and my discussion will leave many of them unexplored. You will
probably never encounter them, and if you do, you will have
entered an advanced Swift world outside the scope of this
discussion. To give an obvious example, readers may be surprised
to find that I never mention Swift playgrounds or the REPL. My
focus here is real-life iOS programming, and my explanation of
Swift therefore concentrates on those common, practical aspects
of the language that, in my experience, actually come into play in
the course of programming iOS.
Part II turns to Xcode, the world in which all iOS programming
ultimately takes place. It explains what an Xcode project is and
how it is transformed into an app, and how to work comfortably
and nimbly with Xcode to consult the documentation and to write,
navigate, and debug code, as well as how to bring your app
through the subsequent stages of running on a device and
submission to the App Store. There is also a very important
chapter on nibs and the nib editor (Interface Builder), including
outlets and actions as well as the mechanics of nib loading;
however, such specialized topics as autolayout constraints in the
nib are postponed to the other book.
Part III introduces the Cocoa Touch framework. When you
program for iOS, you take advantage of a suite of frameworks
provided by Apple. These frameworks, taken together, constitute
Cocoa; the brand of Cocoa that provides the API for programming
iOS is Cocoa Touch. Your code will ultimately be almost entirely
about communicating with Cocoa. The Cocoa Touch frameworks
provide the underlying functionality that any iOS app needs to
have. But to use a framework, you have to think the way the
framework thinks, put your code where the framework expects it,
and fulfill many obligations imposed on you by the framework. To
make things even more interesting, Cocoa uses Objective-C, while
you’ll be using Swift: you need to know how your Swift code will
interface with Cocoa’s features and behaviors. Cocoa provides
important foundational classes and adds linguistic and
architectural devices such as categories, protocols, delegation,
and notifications, as well as the pervasive responsibilities of
memory management. Key–value coding and key–value observing
are also discussed here.
The reader of this book will thus get a thorough grounding in the
fundamental knowledge and techniques that any good iOS
programmer needs. The book itself doesn’t show how to write any
particularly interesting iOS apps, but it does constantly use my own
real apps and real programming situations to illustrate and motivate
its explanations. And then you’ll be ready for Programming iOS 12,
of course!
Versions
This book is geared to Swift 4.2, iOS 12, and Xcode 10.
In general, only very minimal attention is given to earlier versions of
iOS and Xcode. It is not my intention to embrace in this book any
detailed knowledge about earlier versions of the software, which is,
after all, readily and compendiously available in my earlier books.
The book does contain, nevertheless, a few words of advice about
backward compatibility (especially in Chapter 9).
A word about method names. I generally give method names in
Swift, in the style of a function reference (as described in Chapter 2)
— that is, the name plus parentheses containing the parameter
labels followed by colon. Now and then, if a method is already under
discussion and there is no ambiguity, I’ll use the bare name. In a few
places, such as Appendix A, where the Objective-C language is
explicitly under discussion, I use Objective-C method names.
Please bear in mind that Apple continues to make adjustments to
the Swift language. I have tried to keep my code up-to-date right up
to the moment when the manuscript left my hands; but if, at some
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
future time, a new version of Xcode is released along with a new
version of Swift, some of the code in this book, and even some
information about Swift itself, might be slightly incorrect. Please
make allowances, and be prepared to compensate.
Screenshots of Xcode were taken using Xcode 10 under macOS
10.13 High Sierra. I have not upgraded my machine to macOS 10.14
Mojave, because at the time of this writing it was too new to be
trusted with mission-critical work. If you are braver than I am and
running Mojave, your interface may naturally look slightly different
from the screenshots (especially if you’re using “dark mode”), but
this difference will be minimal and shouldn’t cause any confusion.
Acknowledgments
My thanks go first and foremost to the people at O’Reilly Media who
have made writing a book so delightfully easy: Rachel Roumeliotis,
Sarah Schneider, Kristen Brown, Dan Fauxsmith, Adam Witwer, and
Sanders Kleinfeld come particularly to mind. And let’s not forget my
first and long-standing editor, Brian Jepson, whose influence is
present throughout.
As in the past, I have been greatly aided by some fantastic software,
whose excellences I have appreciated at every moment of the
process of writing this book. I should like to mention, in particular:
git (http://git-scm.com)
Sourcetree (http://www.sourcetreeapp.com)
TextMate (http://macromates.com)
AsciiDoc (http://www.methods.co.nz/asciidoc)
Asciidoctor (http://asciidoctor.org)
BBEdit (http://barebones.com/products/bbedit/)
EasyFind
(http://www.devontechnologies.com/products/freeware.html)
Snapz Pro X (http://www.ambrosiasw.com)
GraphicConverter (http://www.lemkesoft.com)
OmniGraffle (http://www.omnigroup.com)
The book was typed and edited entirely on my faithful Unicomp
Model M keyboard (http://pckeyboard.com), without which I could
never have done so much writing over so long a period so painlessly.
For more about my physical work environment, see
http://matt.neuburg.usesthis.com.
Constant width
Used for program listings, as well as within paragraphs to refer to
program elements such as variable or function names, databases,
data types, environment variables, statements, and keywords.
NOTE
This element signifies a general note.
WARNING
This element indicates a warning or caution.
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/ios12-prog-fundamentals.
To comment or ask technical questions about this book, send email
to bookquestions@oreilly.com.
For more information about our books, courses, conferences, and
news, see our website 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
Part I. Language
This part of the book teaches the Swift language, from the ground
up. The description is rigorous and orderly. Here you’ll become
sufficiently conversant with Swift to be comfortable with it, so that
you can proceed to the practical business of actual programming.
Chapter 1 surveys the structure of a Swift program, both
physically and conceptually. You’ll learn how Swift code files are
organized, and you’ll be introduced to the most important
underlying concepts of the object-oriented Swift language:
variables and functions, scopes and namespaces, object types
and their instances.
Chapter 2 explores Swift functions. We start with the basics of
how functions are declared and called; then we discuss
parameters — external parameter names, default parameters,
and variadic parameters. Then we dive deep into the power of
Swift functions, with an explanation of functions inside functions,
functions as first-class values, anonymous functions, functions as
closures, curried functions, and function references and selectors.
Chapter 3 starts with Swift variables — their scope and lifetime,
and how they are declared and initialized, along with features
such as computed variables and setter observers. Then some
important built-in Swift types are introduced, including Booleans,
numbers, strings, ranges, tuples, and Optionals.
Chapter 4 is all about Swift object types — classes, structs, and
enums. It explains how these three object types work, and how
you declare, instantiate, and use them. Then it proceeds to
polymorphism and casting, protocols, generics, and extensions.
The chapter concludes with a discussion of Swift’s umbrella types,
such as Any and AnyObject, and collection types — Array,
Dictionary, and Set (including option sets).
Chapter 5 is a miscellany. We start with Swift’s flow control
structures for branching, looping, and jumping, including error
handling. Then I describe Swift access control (privacy),
introspection (reflection), and how to create your own operators.
There follows a discussion of some recently added Swift language
features: synthesized protocol implementations, key paths, and
dynamic member lookup. The chapter concludes by considering
Swift memory management.
Chapter 1. The Architecture of
Swift
It will be useful at the outset for you to have a general sense of how
the Swift language is constructed and what a Swift-based iOS
program looks like. This chapter will survey the overall architecture
and nature of the Swift language. Subsequent chapters will fill in the
details.
Ground of Being
A complete Swift command is a statement. A Swift text file consists
of multiple lines of text. Line breaks are meaningful. The typical
layout of a program is one statement, one line:
print("hello")
print("world")
print("hello"); print("world")
You are free to put a semicolon at the end of a statement that is last
or alone on its line, but no one ever does (except out of habit,
because C and Objective-C require the semicolon):
print("hello");
print("world");
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Conversely, a single statement can be broken into multiple lines, in
order to prevent long statements from becoming long lines. But you
should try to do this at sensible places so as not to confuse Swift.
For example, after an opening parenthesis is a good place:
print(
"world")
class Dog {
func bark() {
print("woof")
}
}
Swift is a compiled language. This means that your code must build
— passing through the compiler and being turned from text into
some lower-level form that a computer can understand — before it
can run and actually do the things it says to do. The Swift compiler
is very strict; in the course of writing a program, you will often try to
build and run, only to discover that you can’t even build in the first
place, because the compiler will flag some error, which you will have
to fix if you want the code to run. Less often, the compiler will let
you off with a warning; the code can run, but in general you should
take warnings seriously and fix whatever they are telling you about.
The strictness of the compiler is one of Swift’s greatest strengths,
and provides your code with a large measure of audited correctness
even before it ever runs.
The Swift compiler’s error and warning messages, however, range
from the insightful to the obtuse to the downright misleading. You
will often know that something is wrong with a line of code, but the
Swift compiler will not be telling you clearly exactly what is wrong or
even where in the line to focus your attention. My advice in these
situations is to pull the line apart into several lines of simpler code
until you reach a point where you can guess what the issue is. Try to
love the compiler despite the occasional unhelpful nature of its
messages. Remember, it knows more than you do, even if it is
sometimes rather inarticulate about its knowledge.
Everything Is an Object?
In Swift, “everything is an object.” That’s a boast common to various
modern object-oriented languages, but what does it mean? Well,
that depends on what you mean by “object” — and what you mean
by “everything.”
Let’s start by stipulating that an object, roughly speaking, is
something you can send a message to. A message, roughly
speaking, is an imperative instruction. For example, you can give
commands to a dog: “Bark!” “Sit!” In this analogy, those phrases are
messages, and the dog is the object to which you are sending those
messages.
In Swift, the syntax of message-sending is dot-notation. We start
with the object; then there’s a dot (a period); then there’s the
message. (Some messages are also followed by parentheses, but
ignore them for now; the full syntax of message-sending is one of
those details we’ll be filling in later.) This is valid Swift syntax:
fido.bark()
rover.sit()
let sum = 1 + 2
let s = 1.description
extension Int {
func sayHello() {
print("Hello, I'm \(self)")
}
}
1.sayHello() // outputs: "Hello, I'm 1"
let one = 1
var two = 2
Once the name exists, you are free to use it. For example, we can
change the value of two to be the same as the value of one:
let one = 1
var two = 2
two = one
The last line of that code uses both the name one and the name two
declared in the first two lines: the name one, on the right side of the
equal sign, is used merely to refer to the value inside the shoebox on
e (namely 1); but the name two, on the left side of the equal sign, is
used to replace the value inside the shoebox two. A statement like
that, with a variable name on the left side of an equal sign, is called
an assignment, and the equal sign is the assignment operator. The
equal sign is not an assertion of equality, as it might be in an
algebraic formula; it is a command. It means: “Get the value of
Random documents with unrelated
content Scribd suggests to you:
the score of former battles secure for him the allegiance of his
people when his vigor had passed. This was all because in spite of
the modicum of respect that all must yield to old age at its best, the
violent nature of the Periclean politics and the warlike temper of
early days made vigor in their leaders a necessity. The nation was
strong, always seeking to advance and enlarge, and its maxim
seemed to be that of Hesiod, “Work for youth; counsel for maturity;
prayers for old age.” The Greeks, realizing the danger of relying too
much upon experience as the source of wisdom, saw that when the
maturity of age is passed and the power of decision begins to wane,
trusting to the leadership of the old may be dangerous. By a law
often relied on, old men could be brought into court by their children
and be found incapable of managing their property, which was then
transferred to their heirs; and this helps to explain why sometimes
old people, beginning to feel their uselessness, committed suicide
rather than become an encumbrance.
53
Plato makes one of his characters say:
Plato did not himself agree with this view but thought the cause
of this discontent lay not in age itself but in character. Still the
humanist view of life does tend to some such position, and the
Greeks really felt that it was better to be the humblest citizen of
Athens than to rule in Hades.
Two unique characters stand out with great clearness and
significance. The first is that of the Homeric Nestor, who had lived
through three generations of men and in whom Anthon says Homer
intended to exemplify the greatest perfection of which human nature
is capable. His wisdom was great, as was his age, and both grew
together. In his earlier years he had been as great in war as he
became in counsel later. Very different is the figure of Tithonus,
whom Tennyson has made the theme of one of his oft-quoted
poems. He was a mortal, the son of a king, but Aurora became so
enamored of him that she besought Zeus to confer upon him the gift
of immortality. The ruler of Olympus granted her prayer and
Tithonus became exempt from death. But the goddess had forgotten
to crave youth along with immortality and accordingly, after his
children had been born, old age slowly began to mar the visage and
form of her lover and spouse. When she saw him thus declining she
still remained true to him, kept him “in her palace, on the eastern
margin of the Ocean stream, ‘giving him ambrosial food and fair
garments.’ But when he was no longer able to move his limbs she
deemed it the wisest course to shut him up in his chamber, whence
his feeble voice was incessantly heard. Later poets say that out of
compassion she turned him into a cicada.”
It is gratifying to turn from the depressing attitude toward old
age that was characteristic of the Hellenic mind as a whole, because
it came nearer than any other to being the embodiment of eternal
youth, and to glance at the unique and, we must believe on the
whole, very wholesome and suggestive relation that so often
subsisted between men, not to be sure very old (unless in the case
of Socrates) but aging and young men and even boys.
It was assumed that every well-born and -bred young male must
have an older man as his mentor and to be without one was, to
some degree, regarded as discreditable. Thus juniors sometimes
came to vie with each other in their efforts to win the regard of their
seniors, especially if they were prominent; while the latter, in turn,
felt that it was a part of their duty to the community and to the state
to respond to such advances, even to make them. These friendships
between ephebics and sages were, at their best, highly
advantageous to both. The man embodied the boy’s ideal at that
stage of life when he realized that all excellencies were not
embodied in his father and when home relations were merging into
those of citizenship. To win the personal attention and interest of a
great man who would occasionally exercise the function of teacher,
foster parent, guardian, godfather, adviser, or patron, brought not
only advantage but distinction if the youth was noble and beautiful.
On the other hand, Plato thought no man would wish to do or say a
discreditable thing in the presence of a youth who admired him but
would wish to be a pattern or inspirer of virtue. He seems to have
been the first to realize that there is really nothing in the world quite
so worthy of love, reverence, and service, as ingenuous youth fired
with the right ambitions and smitten with a passion to both know
and be the best possible. The period between the dawn of sex and
complete nubility has always been the chief opportunity of the true
teacher or initiator of its apprentice into life.
Here we must recall the very pregnant sense in which, as I have
tried in my Adolescence to set forth at greater length, education in
its various implications began in the initiations of youth by their
elders into the pubertal stage of life and slowly extended upward
toward the university, and downward toward the kindergarten, as
civilization advanced. The world has always felt that these pre-
marital years, when the young have such peculiar needs and are
subjected to so many dangers, are the great opportunity for the
transmission of knowledge and influence from the older to the
younger generation.
Thus while Socrates loved to mingle with men of all classes and
ages, his most congenial companions were those of a younger
generation. With the gracious boy, Charmides, “beautiful in mind and
body, a charming combination of moral dignity and artless
sprightliness,” he discussed temperance in the presence of his
guardian, Critias. With Theætetus, “the younger Socrates,” like his
master more beautiful in mind than in body, he conversed about the
nature of knowledge, in the presence of his tutor. With the fair and
noble young Lysis, invoked to do so by his lover, Hypothales, he
discourses on the right words or acts best calculated to ingratiate
himself with his ward, and the theme is friendship. In the presence
and with the coöperation of four youths he discusses courage with
General Laches, and to young Clineas and his adviser he narrates his
amusing encounter with Euthydemus and his brother, the bumptious
young Sophists, the “eristic sluggers.” He explains the true nature of
his own art to Ion, the Homeric rhapsodist. In the Meno he brings
out the essential points of the forty-seventh proposition of Euclid
54
from the mind of an ignorant slave boy.
This relation of old and younger men was thought to keep youth
plastic, docile, and receptive, if not a trifle feminine. Plato would
have these pairs of friends fight side by side to inspire each other
with courage. But this relation, as we all know, had its dangers and
often lapsed to homosexuality and inversion. In the Symposium,
Alcibiades, that most beautiful and alluring of male coquettes,
describes Socrates as a paragon of chastity because he remained
cold and unmoved by all the seductive blandishments he could bring
to bear upon him. This vice, now so fully explored by Krafft-Ebing,
Tarnowski, Moll, Ellis, and Freud and his disciples, is favored by war,
the seclusion of women as in Turkey, and even by female virtue; but
the Platonic view was that true love was a wisdom or philosophy,
although possibly they did not realize that even the custom of the
Sophists, who first took pay for teaching—a practice they thought
profanation—was nevertheless a step toward the reform of degraded
boy love.
The chief function of wise and older men toward their juniors,
they thought, was to prevent the premature hardening of opinions
into convictions and to keep their minds open and growing. As we
now often say that the chief function of religion and sex is to keep
each other pure, so they thought that wisdom culminated in eros,
which in turn found its highest deployment in the love of knowledge,
which Aristotle later described as the theoretic life, the attainment of
which he deemed the supreme felicity of man. From all this it follows
that those who achieve complete ideal senescence are those who
have entirely sublimated eroticism into the passion for truth and
pursue it with the same ardor that in their prime attracted them to
the most beautiful of the other sex; and that their chief function to
the next generation is to lay in it the foundations for the same
gradual transfer and transformation of it as old age advances.
55
Aristotle’s physical theory of old age is that heat is lost by
gradual dissipation, very little remaining in old age—a flickering
flame that a slight disturbance could put out. The lung hardens by
gradual evaporation of the fluid and so is unable to perform its office
of heat regulation. He assumes that heat is gradually developed in
the heart. The amount produced is always somewhat less than that
which is given off and the deficiency has to be made good out of the
stock with which the organism started originally, that is, from the
innate heat in which the soul was incorporate. This eventually is so
reduced by constant draughts made upon it that it is insufficient to
support the soul. The natural span of life, he says, differs greatly in
length in different species, due to material constitution and the
degree of harmony with the environment. But still, as a general rule,
big plants and animals live longer than smaller ones; sanguineous or
vertebrates longer than invertebrates; the more perfect longer than
the less perfect; and long gestation generally goes with long
duration. Thus bulk, degree of organization, period of gestation, are
correlated. Great size goes with high organization.
56
In his Rhetoric, as is well known, Aristotle gives old age an
unfavorable aspect. He says in substance that the old have lived
many years and been often the victims of deception, and since vice
is the rule rather than the exception in human affairs, they are never
positive about anything. They “suppose” and add “perhaps” or
“possibly,” always expressing themselves in doubt and never
positively. They are uncharitable and ever ready to put the worst
construction upon everything. They are suspicious of evil, not
trusting, because of their experience of human weakness. Hence
they have no strong loves or hates but go according to the precept
of bias. Their love is such as may one day become hate and their
hatred such as may one day become love. The temper of mind is
neither grand nor generous—not the former because they have been
too much humiliated and have no desire to go according to anything
but mere appearances, and not the latter because property is a
necessity of life and they have learned the difficulty of acquiring it
and the facility with which it may be lost. They are cowards and
perpetual alarmists, exactly contrary to the young; not fervent, but
cold. They are never so fond of life as on their last day. Again, it is
the absent which is the object of all desire, and what they most lack
they most want. They are selfish and inclined to expediency rather
than honor; the former having to do with the individual and the
latter being absolute. They are apt to be shameless rather than the
contrary and are prone to disregard appearances. They are
dependent for most things. They live in memory rather than by
hope, for the remainder of their life is short while the past is long,
and this explains their garrulity. Their fits of passion though violent
are feeble. Their sensual desires have either died or become feeble
but they are regulated chiefly by self-interest. Hence they are
capable of self-control, because desires have abated and self-interest
is their leading passion. Calculation has a character that regulates
their lives, for while calculation is directed to expediency, morality is
directed to virtue as its end. Their offenses are those of petty
meanness rather than of insolence. They are compassionate like the
young, but the latter are so from humanity while the old suppose all
manner of sufferings at their door. When the orator addresses them
57
he should bear these traits in mind. Elsewhere he says a happy old
age is one that approaches gradually and without pain and is
dependent upon physical excellence and on fortune, although there
is such a thing as a long life even without health and strength.
Thus, on the whole, the Greeks took a very somber view of old
age. They prized youth as perhaps no other race has ever done and
loved to heighten their appreciation of it by contrasting it with life in
its “sere and yellow leaf.” Pindar says in substance that darkness, old
age, and death never seemed so black as by contrast with the
glories of the great festivals and games which every few years
brought together all those who loved either gold or glory. Socrates,
who refused to flee from his fate and calmly drank hemlock at the
age of seventy, and Plato, who lived to be an octogenarian, must, on
the whole, be regarded as exceptions, and conceptions of a future
life were never clear and strong enough to be of much avail against
the pessimism that in bright Hellas clouded the closing scenes of
life’s drama.
When we turn to Rome, we have, on the whole, a more
favorable view. Even in the early stages of Roman life, family and
parental authority were well developed and in Roman law the patria
potestas gave the head of the family great dignity and power. This
term designates the aggregate of those peculiar powers and rights
that, by the civil law of Rome, belonged to the head of a family in
respect to his wife, children (natural or adopted) and more remote
descendants who sprang from him through males only. Anciently it
was of very extensive scope, embracing even the power of life and
death; but this was greatly curtailed until finally it meant but little
more than a right of the paterfamilias to hold his own property or
58
the acquisitions of one under his power.
The Roman Senate was, as the etymology of the word suggests,
a body of old men; and as the Romans had an unprecedented
genius for social and political organization, the wisdom necessary for
exercising successfully administrative functions, which age alone can
give, had greater scope. In this respect the Catholic Church later and
its canon law were profoundly influenced by and, indeed, as Zeller
has shown in his remarkable essay on the subject, derived most of
its prominent features directly from the political organization of
ancient Rome, also giving great authority to presbyters, elders, and
affording exceptional scope to the organizing ability that comes to its
flower in later life. Jesus was young and Keim believes that all His
disciples were even younger. Those who created ecclesiastical
institutions, however, were far older.
59
In Cicero’s De Senectute we have a remarkably representative
statement put into the mouth of the old man, Cato, as to how aging
Romans regarded their estate, and I think the chief impression in
reading this remarkable document is the vast fund of instances of
signal achievements of old men that are here brought together. This
will be apparent from the following brief résumé.
Cato in his old age is approached by youths who want to know
what he can tell them about life. He commends their interest in age
and tells them he has himself just begun to learn Greek, on which he
spent much time in later years. After the first few pages the treatise
becomes almost entirely a monologue of Cato. Every state is irksome
to those who have no support within and do not see that they owe
happiness to themselves. We must not say old age creeps on after
manhood, manhood after youth, youth after childhood, etc. Each
age has its own interests—spring for blossoms, autumn for fruit. The
wise submit and do not, like the giants, war against the gods. There
are very many instances of those who outlived enjoyment and found
themselves forsaken, but of more who won notable renown and
respect. Perhaps the greatest merit of this book is the instances of
noble old age that abound.
Many are great owing to the reputation of their country and
would be small in other lands. To the very poor old age can never be
very attractive. Think on your good deeds. When Marcus died, Cato
long knew no other man to improve by. The four evils charged to old
age are: (1) it disables from business, (2) it makes the body infirm,
(3) it robs of pleasure, (4) it is near death. He takes these up in
detail. The downfall of great states is “generally owing to the giddy
administration of inexperienced young men”; and, on the contrary,
tottering states have been saved by the old. The young are all
ignorant orators. Memory fails in age only if not exercised, and this
is true of all abilities. Sophocles wrote his Œdipus to defy those who
called him a dotard. Democritus, Plato, Socrates, Zeno, and
Cleanthes are cited. Many old men cannot submit to idleness but
grow old learning something new every day, like Solon. Although the
voice may be low, it may have more command. We should no more
repine when middle life leaves us than we do when childhood
departs. The adult does not mourn that he is no longer a boy. All
must prepare themselves against old age and mitigate its natural
infirmities.
The stage delights in weak, dissolute old fellows worthy of
contempt and ridicule. Age must support its proper rights and
dignities and not give them weakly away. We must recall at night all
we have said or done during the day. As to the third, old age being
incapable of pleasure, the great curse is indulgence of passion, for
which men have betrayed their country. Governments have been
ruined by treachery, for lust may prompt to any villainy. Reason is
the best gift of heaven, but the highest rapture of feeling makes
reflection impossible. Cato then describes with much detail the
charm of country life—Cincinnatus, etc. We might well wish our
enemies were guided by pleasure only for then we could master
them more easily. The old man is dead to certain enjoyments. He
does not so much prize the convivium for food as for talk. We must
not choose only companions of our own age for there will be few of
these left. A talk should turn to the subjects proposed by the master
of the feast, the cups be cooling. He says “I thank the gods I am got
rid of that tyranny” (venery). He does not want or even wish it in
any form.
Far above the delights of literature or philosophy are the charms
of country life, and he describes at length the various methods of
vine culture, fertilization, improving barren soil, irrigation, orchards,
cattle, bees, gardens, flowers, tree planting, etc. The farmer can say,
like the ancient Semites when offered gold, that they wanted none
for it was more glorious to command those who valued it than to
possess it. Then follow many instances of old people who have
retired to the country and perhaps even have been called from their
farms to great tasks of state. He advises reading Xenophon. An old
age thus spent is the happiest period if attended with honor and
respect. Old men are miserable if they demand the defense of
oratory. In the college of augurs old men have great dignity. Some
wines sour with age but others grow better and richer. A gravity with
some severity is allowed, but never ill nature. Covetousness is most
absurd because what is left of life needs little.
The young should be trained to envisage death. Youth in its
greatest vigor is subjected to more diseases than old age. If men too
young governed the state, all government would fall. The old have
already attained what the young only hope for, namely, long years.
No actor can play more than one rôle at once. It takes more water
to put out a hot fire than a spent one. The young are more prone to
die by violence, the old by over-ripeness. The old can oppose tyrants
because these can only kill; and their life, being shorter, is worth far
less. The young and old should meditate on death till it becomes
familiar and this only makes the mind free and easy. Many a soldier
has rushed into the mêlée, with no result, when he knew he would
be cut to pieces, and Marcus Atilius Regulus went back to his
enemies for certain torture and death because he had promised.
There is a certain satiety of each stage of life, and always one is
fading as another warms up.
Perhaps, Cato concludes, our minds are an efflux of some
universal mind, and there may be an argument for preëxistence. We
have not only interest in, but a kind of right to, posterity. The wisest
accept death most easily, although it is by no means clear whether
we are dissolved or there is a personal continuation.
Roman authors quote “many cases of great longevity,” and
Onomocritus, an Athenian, tells us that certain men of Greece, and
even entire families, enjoyed perpetual youth for centuries. Old
Papalius was believed to have lived 500 years and a Portugee, Faria,
300. Pliny tells us of a king who died in his eighty-second year.
Strabo says that in the Punjab people lived over 200 years.
Epaminondas had seen three centuries pass. Pliny tells us that
when, in the reign of Vespasian, statistics of all centenarians
between the Apennines and the Po were collected, there were more
than a hundred and seventy of them out of a population of three
million, six of whom lived over 150 years. According to Lucian,
Tiresias lived 600 years on account of the purity of his life, and the
inhabitants of Mount Ethos had the faculty of living a century and a
half. He tells us of an Indian race, the Seres who, because of
temperate life and very scanty food, lived 300 years, while Pliny tells
of an Illyrian who lived 500 and the king of Cyprus who outlived 160
years. Litorius of Aetolia was happiest among mortals for he had
attained 200 years. Apolonius, the grammarian, outdoes all others
and tells of people who lived thousands of years.
Of the condition and status of old people all through the
Christian centuries down to the age of authentic statistics we know
very little.
Roger Bacon tells us of a remarkable man who appeared in
Europe in 1245 and in whom everyone was interested. He claimed
that he had attended the Council of Paris in a.d. 362 and also the
baptism of Clovis. Bacon’s skepticism reduced the claim of this
unknown man to 300 years. In 1613 was published at Turin the life
of a man who is said to have lived nearly 400 years, enjoying full use
of all his faculties; and in the seventeenth century a Scotchman,
MacCrane, lived 200 years and talked of the Wars of the Roses. So
the lives of the saints are rich in old people—St. Simeon is said to
have lived 107 years; St. Narcissus, 165; St. Anthony, 105; the
hermit, Paul, 113; while the monks of Mount Ethos often reached
the age of 150, as did the first bishop of Ethiopia. Although there
are, of course, no vital statistics, there are many reasons to believe
that the average length of human life was shorter and that old
people in general, although, of course, not without remarkable
exceptions, enjoyed little respect. Descriptions of them sometimes
appear in miracle plays, more commonly in the form of caricatures,
as is often the case on the modern stage, where the personification
of old people is often a specialty. There are dotards and fatuities
galore and the more dignified figures like King Lear or even Shylock
are represented as morally perverse or mentally unsound.
Here should be mentioned the remarkable theory of witchcraft
60 61
elaborated by Karl Pearson. W. Notestein tells us that by
accounting as carefully as the insufficient evidence permits it would
seem that “about six times as many women were indicted as men,”
and also that there were “twice as many married women as
spinsters,” which is less in accord with tradition. From his account, as
well as from the old chapter of C. Mackay on the “Witch Mania” (in
his Popular Delusions) and also from an interesting study by G. L.
62
Kittredge, it would seem that the first accusations of witchcraft
were made against old, middle-aged, and young women almost
indiscriminately, while in a later stage of the delusion attention
focused on old women, influenced by folklore, which tends to make
them hags.
Pearson’s theory, developed with great ingenuity, is that
witchcraft is a revival of a very old and widespread matriarchate
wherein woman not only ruled but society was everywhere
permeated by her genius, and paternity was unknown. The key to
this older civilization was the development of woman’s intuitive
faculty under the stress of child-bearing and -rearing. The mother-
age in its diverse forms has been a stage of social growth for
probably all branches of the human race. With its mother-right
customs it made a social organization in which there was more unity
of interest, fellowship, partnership in property and sex than we find
in the larger social units of to-day. Hence feminists may well look
back to this as a golden age, despite the fact that it was in many
respects cruel and licentious. It shows that those who talk of
absolute good and bad and an unchanging moral code may help to
police but can never reform society.
Pearson proceeds to argue that certain forms of medieval
witchcraft are fossils of the old mother-age and more or less
perverted rites and customs of a prehistoric civilization, and even
holds that the confessions wrung from poor old women by torture
have a real scientific value for the historian of a far earlier stage of
life. Primitive woman, thus, once had a status far higher and very
different from anything she has since enjoyed. Man as husband and
father had no place but came later. Aging women in the matriarchate
were depositaries of tribal lore and family custom, and the “wise
one,” “sibyl,” or “witch” passed all this along, as she did her herb-
lore. She domesticated the small animals—goat, goose, cat, hen;
devised the distaff, spindle, pitchfork, broom (but not the spear, axe,
or hammer); and presided over rites in which there were symbols of
agricultural and animal fertility and abundant traces of licentiousness
and impurity in the sacred dances and ceremonies. “Witch” means
“wiseacre,” “one who knows,” and some were good and some bad
dames or beldames. The former brought good luck; the latter,
famine, plague, etc. All witches have weather wisdom, and a
descendant of the Vola or Sibyl is, in the Edda, seated in the midst
of the assembly of the gods and could produce thunder, hail, and
rain. Tacitus tells us of men who took the part of priestesses,
probably in female attire. Kirmes is a festival lasting several days,
primarily for dedicating a church, although it has many features of
the celebration of a goddess, who in Christian demonology was first
converted into the devil’s mother or grandmother and invested with
most of the functions of old witches. These, in the witches’ sabbath,
came more to devolve upon her son. In Swabia the witch stone is an
old altar and the ceremonies about it suggest marriage. The devil is
a professional sweetheart; his mother, a person of great importance,
was supposed once to have built a palace on the Danube, to hunt
with black dogs, and to be related to Frau Holda. She watered the
meadows in “Twelfth Night” and punished idle spinsters. The devil’s
mother is only a degraded form of the goddess of fertility and
domestic activity and her worship was once associated not only with
licentiousness but with human sacrifice. It was these women who
were primarily in league with the devil and once a year must dance
all night. The hag is the woman of the woods who knows and
collects herbs, especially those that relieve the labors of childbirth.
The priestess of the old civilization became a medicine woman and
midwife, the goddess of fertility being killed in the autumn that she
may be rejuvenated in the spring. Thus the witch is a relic of the
priestess or goddess of fertility, and the hostility they sometimes
exhibit for marriage was because at this stage it was not monogamic
but group marriage.
Thus Pearson thinks that Walpurgis customs bring out most of
the weak and strong points of ancient woman’s civilization, fossils of
which lurk under all the folklore of witchcraft. Here we find the
rudiments of medicine, domestication of small animals, cultivation of
vegetables, domestic and household arts, the pitchfork—which was
once the fire-rake—etc. All of these are woman’s inventions and
were necessary for the higher discoveries. Although he did not
invent them, man later made woman use them. The primitive savage
knows nothing of agriculture, spinning, and herbs, but his wife does.
It is not he but she who made these symbols of a female deity. The
fertility, resource, and inventiveness of woman arose from the
struggle she had to make for the preservation of herself and her
child. Man was quickened by warfare of tribe against tribe, but that
came later. The first struggle was for food and shelter. Thus the
father-age rests on a degenerate form of an older group and is not
the pure outcome of male domination. He thus believes in a direct
line of descent from the old salacious worship of the mother-goddess
and the extravagances of witchcraft, and he finds survivals of this
even in the licensed vice of to-day. Thus this early civilization of
woman handed down a mass of useful customs and knowledge, so
that she was the bearer of a civilization that man has not yet entirely
attained. If many things in her life are vestiges of the mother age,
many in his represent a still lower stratum and the drudgery of the
peasant woman in many parts of Europe represents the extreme of
the reaction brought about by male dominance.
Otis T. Mason and A. F. Chamberlain have stressed the
significance of woman’s work in the early stages of the development
of the human race, and if it be true that in witchcraft we have a
recrudescence of the reactions of man to this preëminence of the
other sex, in which woman in her least attractive form—all shriveled,
toothless, and as a vicious trouble-maker—is caricatured in the long
war of sex against sex, we certainly have here considerable
confirmation of some of the views now represented by John M.
63
Tyler that prehistoric woman led mankind in the early stages of its
upward march toward civilization. In the eternal struggle of old
people to maintain their power against the oncoming generations
which would submerge or sweep them away, witchcraft on this view
represents the very latest stage of a long and losing struggle of old
women for place and influence who in the last resort did not scruple,
handicapped though they were by ugliness, neglect, and contempt,
to cling to the least and last remnants of their ancient prerogatives.
The attitude of children toward old people is interesting and
significant, but it is very difficult to distinguish between their own
indigenous and intrinsic feelings and the conventionalities of respect
and even the outer forms of convention that society has imposed
upon them. Many children live with their grandparents and the
attitude of the latter toward the former makes, of course, a great
difference. Both, especially grandmothers, are prone to be over-
indulgent and often allow children greater liberties than the mother
would—under the influence, doubtless, of the very strong instinct to
win their good-will. But it is very doubtful if the average child loves
the grandmother as much as it is loved by her.
64
Colin Scott obtained 226 reminiscent answers from adults on
the question of how as children they felt toward old people and
found little difference in the sexes in this respect. No less than eighty
per cent expressed negative or pessimistic views; that is, they
disliked old people because they could not run and play; because
they were sometimes cross, solemn, stupid, conceited; perhaps were
thought to envy the young or interfere with childish pleasures, etc.;
while not a few expressed points of aversion to wrinkles, unsteady
gait, untidiness in dress and habits (particularly of eating), slowness,
uncertain voice, loss of teeth, bad pronunciation, etc. Only twenty
per cent took a favorable view of old people, regarding them as
wise, not only about the weather but about other things; as free to
do what they wished; having great power as storytellers; constantly
doing little acts of kindness and sometimes interceding with parents
in their behalf. For the majority of young children the pleasures of
life seem to be essentially over at forty and they look upon people of
that age as already moribund. Very often children are overcome by a
sudden sense of pathos that old people are facing death, the
process of which with lowered vitality seems to them to have already
begun. To some, the very aged, even conventionally loved, are
inwardly repulsive because their weakness and appearance already
begin to seem a little corpse-like; while a few, on the other hand,
are animated by the motive to make old people happy because their
life seems to them so short or because little things please them so
much. It would almost seem from such data as though the modern
child was not sufficiently accustomed to grandparents to have fully
adjusted to them; and, as everyone knows, there is a very strong
and instinctive tendency in children to jeer at and perhaps attempt
ludicrous imitations of old age. At any rate, we have here two
tendencies evidently in greater or less conflict with each other.
65
Mantegazza collected very many views from literature
concerning old age and death and grouped them in two classes,
favorable and unfavorable. The majority of his quotations stigmatize
it as repulsive, crumpled in skin and form, perhaps tearful, squinting,
with mottled skin, loose, distorted teeth, emaciation sometimes
suggesting a skeleton, hardness of hearing, croaking voice, knotted
veins, hemorrhoids, tending to drift into an apologetic attitude for
living like a beggar asking alms or craving pity, with no strong
desires, etc., so that even those who love old people in the bottom
of their hearts often do not want them around. These quotations
stress the garrulousness, untidiness in table manners, carelessness
in dress or toilet, moodiness, exacting nature, and disparagement of
present times in always lauding the past. “Old age is pitiable
because although life is not attractive, death is dreaded.” People
sometimes “seem to themselves and to others to live on because the
gods do not love them.” Life is often described as a “long sorrow, the
last scene of which is always death.” “There are only three events—
to be born, live, and die. A man does not feel it when he is born but
through life he suffers and death is painful, and then he is
forgotten.” “Every tick of the clock brings us nearer to death.” “We
part from life as from the house of a host and not from our own
home.” “One after another our organs refuse their service and
collapse.” “All that lives must die, and all that grows must grow old.”
“Death begins in the cradle.” “The harbor of all things good or bad is
death.” “The elements are in constant conflict with man, slowly
demolishing everything he does and in the end annihilating him.”
On the other hand, some, like the Stoics, have not only affected
to accept death with perfect equanimity but call it the highest good
that God has given men. The Epicurean said death was no evil
because as long as we live it is not present and when it is present
we are not there. Pliny said the gods have given us nothing more to
be desired than brevity of life. Others say that the old may have
weak bodies but normally have good will and this compensates.
Others stress the dignity of age or its steadfastness, its fondness for
children and the young. Sometimes the old become epicures in
eating and connoisseurs in drinking. Some commend as a laudable
ambition the desire of the old to live as long, as well, and as fully as
possible. Others think the love of beauty, especially in nature, is
greater; still others find a new love of order, better knowledge of
self, both physical and mental. He suggests that old age should be
almost a profession, as we have to fit to new conditions. It is
possible then to take larger views, and he says that of the three
attitudes toward death, (1) not to think of it at all, the recourse of
the common and the weak, (2) belief in immortality, a very pleasing
and comforting delusion, and (3) to face and get familiar with it, the
last is by far the highest and hardest. Thus the old must realize that
they are as brittle and fragile as glass, cannot do what they once
could, become ill from slighter causes and recover more slowly, must
especially guard against colds, fatigue, change of habit, and must be
always on their guard not to accept others’ precepts about keeping
themselves in the top of their condition but work out those best for
themselves.
In all ages since civilization began we have frequent outcrops of
the tendency to divide human life into stages, many or few, more or
less sharply marked off one from the other. L. Löw has given us a
comprehensive survey of this subject. There has never been,
however, any general agreement as to these age demarcations save
two, namely, the beginning and the end of sex life, which divides life
into three stages. Child life, as we all know, has lately been divided
into various epochs—the nursling; the pre-school age; the
quadrennium from eight to twelve; puberty; the age of attaining
majority; nubility; the acme of physical ability (for example, for
athletes circa thirty); the beginning of the decline of life, most often
placed between forty and fifty, a stage that has many marked
features of its own; the development of the senium, marked by
impotence, with occasional subdivisions of this stage, as, for
example in Shakespeare: