iOS 12 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 5th Edition Matt Neuburg pdf download
iOS 12 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 5th Edition Matt Neuburg pdf download
https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-3/
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-3/
https://textbookfull.com/product/ios-10-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg/
https://textbookfull.com/product/ios-11-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg/
iOS 13 Programming Fundamentals with Swift Swift Xcode
and Cocoa Basics 1st Edition Matt Neuburg
https://textbookfull.com/product/ios-13-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg/
https://textbookfull.com/product/ios-14-programming-fundamentals-
with-swift-covers-ios-14-xcode-12-and-swift-5-3-7th-edition-matt-
neuburg/
https://textbookfull.com/product/programming-ios-14-11th-edition-
matt-neuburg/
https://textbookfull.com/product/learn-ios-11-programming-with-
swift-4-craig-clayton/
https://textbookfull.com/product/programming-ios-12-dive-deep-
into-views-view-controllers-and-frameworks-1st-edition-matt-
neuburg/
Xc
C o 0,
od
ve a n
e1
rs d
i O Sw
S 1 if t
2, 4
.2
iOS 12
Programming
Fundamentals
with Swift
SWIFT, XCODE, AND COCOA BASICS
Matt Neuburg
FIFTH EDITION
iOS 12 Programming
Fundamentals with Swift
Swift, Xcode, and Cocoa Basics
Matt Neuburg
Boston
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/insti‐
tutional sales department: 800-998-9938 or corporate@oreilly.com.
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]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Part I. Language
1. The Architecture of Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Ground of Being 3
Everything Is an Object? 5
Three Flavors of Object Type 6
Variables 6
Functions 8
The Structure of a Swift File 9
Scope and Lifetime 11
Object Members 13
Namespaces 13
Modules 14
Instances 15
Why Instances? 17
The Keyword self 19
Privacy 20
Design 22
Object Types and APIs 23
Instance Creation, Scope, and Lifetime 25
Summary and Conclusion 25
2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Function Parameters and Return Value 27
Void Return Type and Parameters 31
Function Signature 32
External Parameter Names 32
iii
Overloading 34
Default Parameter Values 35
Variadic Parameters 35
Ignored Parameters 36
Modifiable Parameters 37
Function in Function 40
Recursion 42
Function As Value 42
Anonymous Functions 45
Define-and-Call 51
Closures 52
How Closures Improve Code 54
Function Returning Function 55
Closure Setting a Captured Variable 58
Closure Preserving Its Captured Environment 59
Escaping Closures 60
Curried Functions 60
Function References and Selectors 62
Function Reference Scope 64
Selectors 65
iv | Table of Contents
Subscripts 132
Nested Object Types 135
Instance References 135
Enums 137
Raw Values 138
Associated Values 140
Enum Case Iteration 142
Enum Initializers 143
Enum Properties 144
Enum Methods 145
Why Enums? 146
Structs 147
Struct Initializers, Properties, and Methods 147
Struct As Namespace 149
Classes 149
Value Types and Reference Types 150
Subclass and Superclass 156
Class Initializers 161
Class Deinitializer 169
Class Properties and Methods 170
Polymorphism 172
Casting 175
Casting Down 176
Type Testing and Casting Down Safely 176
Type Testing and Casting Optionals 178
Bridging to Objective-C 178
Type References 180
From Instance to Type 180
Type as Value 181
The Keyword Self 183
Comparing Types 184
Summary of Type Terminology 185
Protocols 186
Why Protocols? 187
Protocol Type Testing and Casting 189
Declaring a Protocol 190
Protocol Composition 191
Optional Protocol Members 192
Class Protocol 194
Implicitly Required Initializers 195
Literal Convertibles 196
Generics 197
Table of Contents | v
Generic Declarations 200
Contradictory Resolution 202
Type Constraints 203
Explicit Specialization 205
Generic Invariance 207
Associated Type Chains 208
Where Clauses 210
Extensions 213
Extending Object Types 213
Extending Protocols 215
Extending Generics 217
Umbrella Types 219
Any 219
AnyObject 221
AnyClass 223
Collection Types 224
Array 224
Dictionary 240
Set 247
vi | Table of Contents
6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
New Project 313
The Project Window 315
The Navigator Pane 317
The Utilities Pane 322
The Editor 323
The Project File and Its Dependents 325
What’s In the Project Folder 326
Groups 327
The Target 328
Build Phases 328
Build Settings 330
Configurations 331
Schemes and Destinations 333
From Project to Built App 335
Build Settings 338
Property List Settings 338
Nib Files 339
Additional Resources 340
Code Files 342
Frameworks and SDKs 343
The App Launch Process 345
The Entry Point 345
UIApplicationMain 346
App Without a Storyboard 348
Renaming Parts of a Project 349
8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
The Documentation Window 385
Class Documentation Pages 386
Quick Help 390
Symbol Declarations 392
Header Files 393
Sample Code 394
Internet Resources 394
Table of Contents | ix
NSSet and Friends 496
NSIndexSet 497
NSNull 498
Immutable and Mutable 498
Property Lists 500
Codable 501
Accessors, Properties, and Key–Value Coding 504
Swift Accessors 505
Key–Value Coding 507
Uses of Key–Value Coding 508
KVC and Outlets 510
Cocoa Key Paths 510
The Secret Life of NSObject 511
x | Table of Contents
Autorelease Pool 547
Memory Management of Instance Properties 549
Retain Cycles and Weak References 550
Unusual Memory Management Situations 552
Notification Observers 552
KVO Observers 554
Timers 554
Other Unusual Situations 556
Nib Loading and Memory Management 556
Memory Management of CFTypeRefs 557
Property Memory Management Policies 559
Debugging Memory Management Mistakes 561
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Table of Contents | xi
Preface
On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐
ment: “We have a new programming language.” This came as a huge surprise to the
developer community, which was accustomed to Objective-C, warts and all, and
doubted that Apple could ever possibly relieve them from the weight of its venerable
legacy. The developer community, it appeared, had been wrong.
Having picked themselves up off the floor, developers immediately began to consider
this new language — Swift — studying it, critiquing it, and deciding whether to use it.
My own first move was to translate all my existing iOS apps into Swift; this was
enough to convince me that Swift deserved to be, and probably would be, adopted by
new students of iOS programming, and that my books, therefore, should henceforth
assume that readers are using Swift.
That decision has proven prophetic. Programmers of iOS have flocked to Swift in
increasing numbers, and Swift itself has only improved. My iOS apps (such as Diabel‐
li’s Theme, LinkSame, Zotz!, TidBITS News, and my Latin and Greek flashcard apps)
have all been rewritten in Swift, and are far easier for me to understand and maintain
than their Objective-C originals.
Xcode 10 comes with Swift 4.2. The language has evolved greatly in its details and in
the nature of its integration with the Cocoa libraries that underlie iOS programming,
but its spirit has remained constant. The Swift language is designed from the ground
up with these salient features:
Object-orientation
Swift is a modern, object-oriented language. It is purely object-oriented: “Every‐
thing is an object.”
Clarity
Swift is easy to read and easy to write. Its syntax is clear, consistent, and explicit,
with few hidden shortcuts and minimal syntactic trickery.
xiii
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 fre‐
quently 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 lan‐
guages would expect.
xiv | Preface
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 documenta‐
tion 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 commu‐
nicate with one another, as well as explaining how your app can be written partly in
Swift and partly in Objective-C.
Preface | xv
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 documenta‐
tion 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 post‐
poned 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 frame‐
work 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 back‐
ward compatibility (especially in Chapter 9).
xvi | Preface
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 dis‐
cussion, 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 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 informa‐
tion 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 writ‐
ing 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)
Preface | xvii
• 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.
xviii | Preface
This book is not intended to disparage Apple’s own documentation and example
projects. They are wonderful resources and have become more wonderful as time
goes on. I have depended heavily on them in the preparation of this book. But I also
find that they don’t fulfill the same function as a reasoned, ordered presentation of
the facts. The online documentation must make assumptions as to how much you
already know; it can’t guarantee that you’ll approach it in a given order. And online
documentation is more suitable to reference than to instruction. A fully written
example, no matter how well commented, is difficult to follow; it demonstrates, but it
does not teach.
A book, on the other hand, has numbered chapters and sequential pages; I can
assume you know views before you know view controllers for the simple reason that
Part I precedes Part II. And along with facts, I also bring to the table a degree of expe‐
rience, which I try to communicate to you. Throughout this book you’ll find me
referring to “common beginner mistakes”; in most cases, these are mistakes that I
have made myself, in addition to seeing others make them. I try to tell you what the
pitfalls are because I assume that, in the course of things, you will otherwise fall into
them just as naturally as I did as I was learning. You’ll also see me construct many
examples piece by piece or extract and explain just one tiny portion of a larger app. It
is not a massive finished program that teaches programming, but an exposition of the
thought process that developed that program. It is this thought process, more than
anything else, that I hope you will gain from reading this book.
Preface | xix
This element signifies a general note.
xx | Preface
For more information, please visit http://oreilly.com/safari.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
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 bookques‐
tions@oreilly.com.
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
Preface | xxi
PART I
Language
This part of the book teaches the Swift language, from the ground up. The descrip‐
tion 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 concep‐
tually. 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 set‐
ter observers. Then some important built-in Swift types are introduced, includ‐
ing 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 branch‐
ing, looping, and jumping, including error handling. Then I describe Swift access
control (privacy), introspection (reflection), and how to create your own opera‐
tors. 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 sur‐
vey 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")
3
print(
"world")
Comments are everything after two slashes in a line (so-called C++-style comments):
print("world") // this is a comment, so Swift ignores it
You can also enclose comments in /*...*/, as in C. Unlike C, C-style comments can
be nested.
Many constructs in Swift use curly braces as delimiters:
class Dog {
func bark() {
print("woof")
}
}
By convention, the contents of curly braces are preceded and followed by line breaks
and are indented for clarity, as shown in the preceding code. Xcode will help impose
this convention, but the truth is that Swift doesn’t care, and layouts like this are legal
(and are sometimes more convenient):
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 occa‐
sional unhelpful nature of its messages. Remember, it knows more than you do, even
if it is sometimes rather inarticulate about its knowledge.
But it is surprising to find that 1 can be followed by a dot and a message. This is legal
and meaningful in Swift (don’t worry about what it actually means):
let s = 1.description
But we can go further. Return to that innocent-looking 1 + 2 from our earlier code.
It turns out that this is actually a kind of syntactic trickery, a convenient way of
expressing and hiding what’s really going on. Just as 1 is actually an object, + is
actually a message; but it’s a message with special syntax (operator syntax). In Swift,
every noun is an object, and every verb is a message.
Perhaps the ultimate acid test for whether something is an object in Swift is whether
you can modify it. An object type can be extended in Swift, meaning that you can
define your own messages on that type. For example, you can’t normally send the say-
Hello message to a number. But you can change a number type so that you can:
extension Int {
func sayHello() {
print("Hello, I'm \(self)")
}
}
1.sayHello() // outputs: "Hello, I'm 1"
Everything Is an Object? | 5
Another Random Document on
Scribd Without Any Related Topics
sense the divine glory may be independent of created beings; but it
is not the primitiv sense of the word, nor the sense which answers
to the original meaning of the Greek doxe, and the Latin gloria.
No right in England and America is so much celebrated as that of
trial by peers; by which is commonly understood, trial by equals. The
right is valuable, but is not derived from the primitiv custom of trial
by equals; on the contrary, it is very questionable whether such a
custom existed prior to Alfred. Yet the trial by peers existed long
before, and can be traced back to the date of the Christian era. The
truth is, the word peer is not derived from the Latin par, equal; but
from the German, or Teutonic bar or par, which signified a
landholder, freeman or judge. The bars were that class of men who
held the fees or property in estates; and from whom the word baron
and the attendant privileges are derived. We have the same root in
baron, baronet, parliament, parish, and many other words, all
implying some degree of authority, eminence or jurisdiction. From
the same word bar or par, (for B and P are convertible letters) the
word peer is derived, as it is used in the common expressions house
of peers, trial by peers. It signified originally, not equals, but judges
or barons. The house of peers in England derives its appellation and
its jurisdiction from the ancient mode of trial by bars or barons; for it
is the final resort in all judicial cases. Yet the ancient English
lawyers, supposing the word to be from the Latin par, equal, have
explained it in that sense, and multiplied encomiums without end
upon the excellence of the privilege. The privilege is valuable, but its
excellence, if it consists in a trial by equals, is modern, compared
with the original custom, which was a trial by barons, or principal
landholders.
It is probable that our modern writers, misunderstanding the term
voluptas, have passed too severe censures upon epicures. The true
primitiv meaning of voluptas was that of pleasurable sensations
arising from innocent gratifications. Our modern word
voluptuousness carries with it a much stronger idea, and hence we
are led into an error reflecting the doctrine of Epicurus, who might
confine his ideas of pleasure to innocent gratifications.
We have been accustomed from childhood to hear the expressions,
the dew falls; the dews of heaven; and it is probable that nine
people out of ten, have never suspected the inaccuracy of the
phrases. But dew is merely the perspiration of the earth; it rises
instead of falling, and rises during the night.[63]
It was also supposed that manna in the eastern countries, came
from above, and it is called in scripture bread from heaven. Yet
manna is a gum, exuding from plants, trees and bushes, when
pierced by certain insects. The truth of this fact was not discovered,
till the middle of the sixteenth century.
Every man knows, when the prices of goods rise, it is said they
become dear; yet when the prices rise in consequence of an
overflowing sum of money in circulation, the fact is that the value of
money falls, and the value of goods remains the same. This
erroneous opinion had an amazing effect in raising popular clamor,
at the commencement of the late revolution.
I will name but one other instance, which has a material influence
upon our moral and religious opinions. It is said in scripture that God
hardened Pharaoh's heart. How? Was there a miracle in the case? By
no means. The manner of speaking leads us into the mistake. The
first cause is mentioned, and not the intermediate cause or causes.
So we should say, that General Washington attacked the British
troops at Monmouth; altho he was at a great distance when the
attack was commenced, and only ordered the attack. I suspect that
similar modes of speaking in scripture often lead superficial minds
into mistakes, and in some instances, giv occasion to infidels to scoff
at passages, which, if rightly understood, would silence all
objections.
This is a fruitful theme, and would lead an ingenious inquirer into a
wide field of investigation. But I have neither time nor talents to do
it justice; the few hints here suggested may have some effect in
convincing my readers of the importance and utility of all candid
researches into the origin and structure of speech; and pave the way
for further investigations, which may assist us in correcting our ideas
and ascertaining the force and beauty of our own language.
No. XIX.
PHILADELPHIA, 1787.
On VOCAL MUSIC.
The establishment of schools for teaching psalmody in this city is a
pleasing institution; but people seem not to understand the design,
or rather are not aware of the advantages which may result from it,
if properly conducted and encouraged. Most people consider music
merely as a source of pleasure; not attending to its influence on the
human mind, and its consequent effects on society. But it should be
regarded as an article of education, useful as well as ornamental.
The human mind is formed for activity; and will ever be employed in
business or diversions. Children are perpetually in motion, and all
the ingenuity of their parents and guardians should be exerted to
devise methods for restraining this activ principle, and directing it to
some useful object, or to harmless trifles. If this is not done, their
propensity to action, even without a vicious motiv, will hurry them
into follies and crimes. Every thing innocent, that attracts the
attention of children, and will employ their minds in leisure hours,
when idleness might otherwise open the way to vice, must be
considered as a valuable employment. Of this kind is vocal music.
There were instances of youth, the last winter, who voluntarily
attended a singing school in preference to the theatre. It is but
reasonable to suppose, that if they would neglect a theatre for
singing, they would neglect a thousand amusements, less engaging,
and more pernicious.
Instrumental music is generally prefered to vocal, and considered as
an elegant accomplishment. It is indeed a pleasing accomplishment;
but the preference given to it, is a species of the same false taste,
which places a son under the tuition of a drunken clown, to make
him a gentleman of strict morals.
Instrumental music may exceed vocal in some nice touches and
distinctions of sound; but when regarded as to its effects upon the
mind and upon society, it is as inferior to vocal, as sound is inferior
to sense. It is very easy for a spruce beau to display a contempt for
vocal music, and to say that human invention has gone beyond the
works of God Almighty. But till the system of creation shall be new
modelled, the human voice properly cultivated will be capable of
making the most perfect music. It is neglected; sol faing is
unfashionable, and that is enough to damn it: But people who have
not been acquainted with the perfection of psalmody, are incapable
of making a suitable comparison between vocal and instrumental
music. I have often heard the best vocal concerts in America, and
the best instrumental concerts; and can declare, that the music of
the latter is as inferior to that of the former, as the merit of a band
box macaroni is to that of a Cato.
Instrumental music affords an agreeable amusement; and as an
amusement it ought to be cultivated. But the advantage is private
and limited; it pleases the ear, but leaves no impression upon the
heart.
The design of music is to awaken the passions, to soften the heart
for the reception of sentiment. To awaken passion is within the
power of instruments, and this may afford a temporary pleasure; but
society derives no advantage from it, unless some useful sentiment
is left upon the heart.
Instruments are secondary in their use; they were invented
originally, not to supercede, but to assist the voice. The first histories
of all nations were written in verse, and sung by their bards. In later
ages, the oaten reed, the harp and the lyre, were found to improve
the pleasures of music; but the neglect of the voice and of sentiment
was reserved for modern corruption. Ignorant indeed is the man,
and possessed of a wretched taste, who can seriously despise the
humble pleasures of vocal music, and prefer the bare harmony of
sounds. Sentiment should ever accompany music; the sounds should
ever correspond with the ideas, otherwise music loses all its force.
Union of sentiment, with harmony of sounds, is the perfection of
music. Every string of the human heart may be touched; every
passion roused by the different kinds of sounds; the courage of the
warrior; the cruelty of the tyrant; anger; grief; love, with all its
sensibilities, are subject to the influence of music. Even brutes
acknowlege its effects; but while they in common with man feel the
effects of a harmony of mere sounds, man enjoys the superior
felicity of receiving sentiment; and while he relishes the pleasures of
chords in sound, he imbibes a disposition to communicate happiness
to society.
Seldom indeed do men reflect on the connexion between the chords
of music and the social affections. Morality is to immorality, what
harmony is to discord. Society detests vice, and the ear is offended
with discordant sounds. Society is pleased and happified with virtue,
and the ear is delighted with harmony. This beautiful analogy points
out the utility of cultivating music as a science. Harsh discordant
sounds excite the peevish malevolent passions; harmonious sounds
correct and soften the rougher passions.
Every person will acknowlege, that love refines the heart, and
renders it more susceptible, and more capable of social virtue. It is
for this reason that men who have particular attachments to women,
or associate much with ladies of delicacy, are more disposed to do
acts of kindness, in every sphere of life, than those who seldom
frequent ladies company. On the other hand, anger, jealousy, envy,
are dissocial passions; and even when they are excited by a single
object, they poison the heart, and disqualify it for exciting the social
affections towards any of the human race. Every institution,
therefore, calculated to prepare the human heart for exerting the
social virtues, and to suppress or check the malignant passions,
must be highly beneficial to society; and such I consider
establishments in favor of vocal music. Happy, indeed, should I feel,
could I see youth devoted every where to the refinement of their
voices and morals; to see them prefer moral or religious pieces to
the indecent songs or low diversions which taint the mind in early
life, and diffuse their pernicious influence through society.
If the poison of the tarantula may be counteracted by music; if the
Spanish ladies are won by nocturnal serenades; if the soldier is
inspired with courage by the martial sounds of the trumpet, and the
Christian impressed with devout sentiments by the solemn tones of
the organ; what advantage may society derive from the softening
harmony of choirs of voices, celebrating the praises of social virtue!
Happy days! when false taste and false opinions shall vanish before
the progress of truth; when princes shall resume their ancient and
honorable task of teaching the young to be good and great; when
an Addison shall be preferred to a Chesterfield; when the wealth of
nations shall be no longer lavished upon fiddlers and dancers; when
the characters of a Benezet and a Washington shall obscure the
glories of a Cæsar; and when no man shall be ashamed to be good,
because it is unfashionable.
No. XX.
NEW YORK, JUNE, 1788.
On MORALITY.
"The principles of morality are little understood among savages,"
says Lord Kaimes, "and if they arrive to maturity among enlightened
nations, it is by slow degrees."
With submission to that writer, I would advance another position
equally true, "that the principles of eating and drinking are little
understood by savages, and if they arrive to maturity among civilized
nations, it is by slow degrees."
The truth is, morality consists in discharging the social duties of life;
and so far as the state of savages requires an intercourse of duties,
the moral principles seem to be as perfect in them as in more
enlightened nations. Savages in a perfectly rude state have little or
no commerce; the transactions between man and man are confined
to very few objects, and consequently the laws which regulate their
intercourse and distribute justice, must be few and simple.[64] But
the crime of murder is as severely punished by savages, as by
civilized nations. Nay, I question whether it is possible to name the
barbarous tribe, which suffers an individual to take the life of
another, upon as easy terms as the modern feudal Barons in Europe
may do that of a vassal; or with the same impunity that a planter in
the West Indies takes the life of a slave. I speak of a time of peace,
and of the conduct of savages towards their own tribes. As to war,
every nation of savages has its arbitrary customs, and so has every
civilized nation. Savages are generally partial and capricious in the
treatment of their prisoners; some they treat with a singular
humanity; and others they put to death with the severest cruelty.
Well, do not civilized people the same? Did a savage ever endure
greater torments, than thousands of prisoners during the late war?
But not to mention the practice of a single nation, at a single period;
let us advert to a general rule among civilized nations; that it is
lawful to put to death prisoners taken in a garrison by storm. The
practice grounded on this rule, is as direct and as enormous a
violation of the laws of morality, as the slow deliberate tortures
exercised by the most barbarous savages on earth.
Well, what are the ideas of savages respecting theft? How do they
differ from those of an enlightened people? Many things are
possessed in common, as provisions taken in hunting, corn, &c.
Ferdinand de Soto relates, that the tribes (and he visited hundreds in
Florida) had public granaries of corn laid up for winter, which was
distributed by authority to each family, according to its number. But
for an individual to take from this common stock without license,
was considered as a criminal defrauding of the public. And with
regard to the few articles, in which individuals acquire private
property, the savages have as correct ideas of meum and tuum, of
theft, trespass, &c. and are as careful to guard private property from
invasion, by laws and penalties, as any civilized people. The laws of
the Creeks, the Cherokees, the Six Nations, &c. with regard to these
and many other crimes, in point of reason and equity, stand on a
footing with those of the most civilized nations; and in point of
execution and observance, their administration would do honor to
any government. Among most savage nations there is a kind of
monarchy which is efficient in administration; and among those
tribes which have had no intercourse with civilized nations, and
which have not been deceived by the tricks of traders; the common
arts of cheating, by which millions of enlightened people get a living
or a fortune, are wholly unknown. This is an incontrovertible fact. I
lately became acquainted with a lad of about twelve years old, who
was taken captiv by the Indians in 1778, while a child, and had
continued with them till about ten years old. He had no recollection
of the time when he was taken, and consequently his mind could not
have been corrupted among the English. When he was restored,
agreeable to the treaty, he was a perfect savage; but what I relate
the circumstance for, is this; the lad was not addicted to a single
vice. He was instant and cheerful in obeying commands; having not
even a disposition to refuse or evade a compliance. He had no
inclination to lie or steal; on the other hand, he was always surprised
to find a person saying one thing and meaning another. In short, he
knew not any thing but honesty and undisguised frankness and
integrity. A single instance does not indeed establish a general rule;
but those who are acquainted with the nativs of America can testify
that this is the general character of savages who are not corrupted
by the vices of civilized nations.
But it is said savages are revengeful; their hatred is hereditary and
perpetual. How does this differ from the hatred of civilized nations? I
question much whether the principle of revenge is not as perfect in
enlightened nations, as in savages. The difference is this; a savage
hunts the man who has offended him, like a wild beast, and
assassinates him wherever he finds him; the gentleman pursues his
enemy or his rival with as much rancor as a savage, and even stoops
to notice little affronts, that a savage would overlook; but he does
not stab him privately; he hazards his own life with that of his
enemy, and one or both are very honorably murdered. The principle
of revenge is equally activ in both cases; but its operation is
regulated by certain arbitrary customs. A savage is open and avows
his revenge, and kills privately; the polite and well bred take revenge
in a more honorable way, when life is to be the price of satisfaction;
but in cases of small affronts, they are content with privately
stabbing the reputation or ruining the fortunes of their enemies. In
short, the passions of a savage are under no restraint; the passions
of enlightened people are restrained and regulated by a thousand
civil laws and accidental circumstances of society.
But it will be objected, if savages understood principles of morality,
they would lay such passions under restraint. Not at all: Civil and
political regulations are not made, because the things prohibited are
in their own nature wrong; but because they produce
inconveniencies to society. The most enlightened nations do not
found their laws and penalties on an abstract regard to wrong; nor
has government any concern with that which has no influence on
the peace and safety of society. If savages, therefore, leave every
man to take his own revenge, it is a proof that they judge it the best
mode of preventing the necessity of it; that is, they think their
society and government safer under such a license, than under
regulations which should control the passions of individuals. They
may have their ideas of the nature of revenge independent of
society; but it will be extremely difficult to prove, that, abstracted
from a regard to a Deity and to society, there is such a thing as right
and wrong. I consider morality merely as it respects society; for if
we superadd the obligations of a divine command, we blend it with
religion; an article in which Christians have an infinit advantage over
savages.
Considering moral duties as founded solely on the constitution of
society, and as having for their sole end the happiness of social
beings, many of them will vary in their nature and extent, according
to the particular state and circumstances of any society.
Among the ancient Britons, a singular custom prevailed; which was,
a community of wives by common consent. Every man married one
woman; but a number, perhaps ten or twelve, relations or neighbors,
agreed to possess their wives in common. Every woman's children
were accounted the children of her husband; but every man had a
share in the common defence and care of this little community.[65]
Was this any breach of morality? Not in the least. A British woman,
in the time of Severus, having become intimate with Julia Augusta,
and other ladies, at the court of Rome, had observed what passed
behind the curtain; and being one day reproached for this custom of
the Britons, as infamous in the women, and barbarous in the men;
she replied, "We do that openly with the best of our men, which you
do privately with the worst of yours." This custom, so far from being
infamous or barbarous, originated in public and private convenience.
It prevented jealousy and the injuries of adultery, in a state where
private wrongs could not easily be prevented or redressed. It might
be an excellent substitute for penal laws and a regular
administration of justice. But there is a better reason for the custom,
which writers seem to have overlooked; and this is, that a
community multiplied the chances of subsistence and security. In a
savage life, subsistence is precarious, for it depends on contingent
supplies by hunting and fishing. If every individual, therefore, should
depend solely on his own good luck, and fail of success, his family
must starve. But in a community of twelve, the probability that some
one would procure provisions is increased as twelve to one. Hence
the community of provisions among most savage nations.[66]
The Britons, when the Romans first visited their island, did not
attend much to the cultivation of the earth. "Interiores plerique,"
says Cæsar, "frumenta non serunt, sed lacte et carne vivunt." By
establishing a community of goods, they secured themselves against
the hazard of want; and by a community of wives and offspring,
they confirmed the obligations of each to superintend the whole; or
rather, changed into a natural obligation what might otherwise
depend on the feebler force of positiv compact. Besides, it is very
possible that personal safety from the invasion of tribes or
individuals, might be another motiv for establishing these singular
communities. At any rate, we must suppose that the Britons had
good civil or political reasons for this custom; for even savages do
not act without reason. And if they found society more safe and
happy, with such a custom than without it, it was most undoubtedly
right.
Should it be said, that a community is prohibited by divine
command; I would answer that it is not presumable that the old
Britons had any positiv revelation; and I do not know that the law of
nature will decide against their practice. The commands given to the
Jews were positiv injunctions; but they by no means extend to all
nations, farther than as they are founded on immutable principles of
right and wrong in all societies. Many of the Mosaic precepts are of
this kind; they are unlimited in their extent, because they stand on
principles which are unlimited in their operation.
Adultery is forbidden in the Jewish laws; and so it is in the codes of
other nations. But adultery may be defined differently by different
nations; and the criminality of it depends on the particular positiv
institutions, or accidental circumstances of a nation. The same
reasons that would render a similar custom in civilized modern
nations highly criminal, might render it innocent and even necessary
among the old Britons. A prohibition to gather sticks on the Sabbath,
under a penalty of death for disobedience, might be founded on
good reasons among the ancient Jews; but it would be hard to prove
that a modern law of the same kind, would be warrantable in any
nation.
No. XXI.
NEW YORK, JUNE, 1788.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com