The Basics 基本

Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. スウィフトは、iOS、macOS、watchOS、そしてtvOSアプリ開発のための新しいプログラミング言語です。にもかかわらず、スウィフトの多くの部分は、あなたのCとObjective-Cでの開発経験からきっとお馴染みのものでしょう。

Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers, Double and Float for floating-point values, Bool for Boolean values, and String for textual data. Swift also provides powerful versions of the three primary collection types, Array, Set, and Dictionary, as described in Collection Types. スウィフトは、全ての基本的なCおよびObjective-C型に関してそれ自身のバージョンを提供します、それには、整数のためのInt、浮動小数点値のためのDoubleFloat、ブール値のためのBool、そして、文字情報データのためのStringを含みます。スウィフトはまた、3つの主要なコレクション型、ArraySet、そしてDictionaryの強力なバージョンを提供します、それは「コレクション型」で記述されます。

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values can’t be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that don’t need to change. Cのように、スウィフトはひとつの識別名によっていろいろな値を保管したり引用したりするために、変数を使います。スウィフトはまた、それの値が変更されることができない変数を広範囲に利用します。これらは定数として知られています、そしてCにおける定数よりずっと強力です。定数は、変わる必要がない値をあなたが扱う時、コードをより安全により明白にする意図でスウィフトを通して使われます。

In addition to familiar types, Swift introduces advanced types not found in Objective-C, such as tuples. Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value. よく知られている型に加えて、スウィフトはObjective-Cで見られない先進の型を導入します、例えばタプルのような。タプルは、あなたに値のグループをつくってあちこち渡すことを可能にします。あなたはタプルを使って、関数から複数の値を1つの混成値として返すことができます。

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Using optionals is similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Not only are optionals safer and more expressive than nil pointers in Objective-C, they’re at the heart of many of Swift’s most powerful features. スウィフトはまたオプショナルの型を導入します、それは値の欠如を取り扱います。オプショナルであるものは、「ひとつの値がある、そしてそれはxに等しい」または「まったく値がない」のどちらかを伝えます。オプショナルの使用は、Objective-Cのポインターでnilを使うことに似ています、しかしそれは、ただクラスだけでなく、どんな型のためにでも働きます。オプショナルはObjective-Cでのnilポインターより安全でさらに表現豊かであるだけでなく、それはスウィフトのたくさんある非常に強力な特徴のうち核心的なものです。

Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code requires a String, type safety prevents you from passing it an Int by mistake. Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that requires a non-optional String. Type safety helps you catch and fix errors as early as possible in the development process. スウィフトは型安全な言語です、それが意味するのは、この言語があなたを助けて、あなたのコードが扱うことができる値の型について明確であるようにすることです。あなたのコードの一部がStringを要求するならば、型安全はあなたが間違ってそれにIntを渡すことを防ぎます。さらに、型安全はあなたがうっかりしてオプショナルStringを、非オプショナルStringを要求するコード部分に渡すことを防ぎます。型安全は、あなたが開発プロセスにおいて可能な限り早期にエラーを捕まえて修復するのを助けます。

Constants and Variables 定数と変数

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant can’t be changed once it’s set, whereas a variable can be set to a different value in the future. 定数と変数は、ひとつの名前(例えばmaximumNumberOfLoginAttemptsまたはwelcomeMessageなど)を特定の型のひとつの値(例えば数10または文字列"Hello"など)と結びつけます。定数の値は、一旦それが設定されるならば変わることができません、一方で変数は将来異なる値に設定されることができます。

Declaring Constants and Variables 定数と変数の宣言

Constants and variables must be declared before they’re used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made: 定数と変数は、それらが使われる前に宣言されなければなりません。あなたは、letキーワードを使って定数を、varキーワードを使って変数を宣言します。ここに定数と変数が、どのようにあるユーザーが行ったログインの試みの数を追跡するために使われることができるかの例があります:

  1. let maximumNumberOfLoginAttempts = 10
  2. var currentLoginAttempt = 0

This code can be read as: このコードは、次のように解釈されることができます:

“Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10. Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.” maximumNumberOfLoginAttemptsと呼ばれるある新しい定数を宣言して、それに10というひとつの値を与える。その後で、currentLoginAttemptと呼ばれる新しい変数を宣言して、それに0の初期値を与える。」

In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt. この例において、許可されるログインの試みの最大数は、最大の値が決して変わらないので、定数として宣言されます。現在のログイン試行の計数は、この値が失敗したログインの試みそれぞれの後で増加する必要があるので、変数として宣言されます。

You can declare multiple constants or multiple variables on a single line, separated by commas: あなたは複数の定数または複数の変数を、コンマで区切ることで1つの行に宣言することができます:

  1. var x = 0.0, y = 0.0, z = 0.0

Note 注意

If a stored value in your code won’t change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change. ある格納された値をあなたのコードにおいて変化させる予定がないならば、常にletキーワードを使ってそれを定数として宣言してください。変更できる必要がある値を保存するためにだけ、変数を使ってください。

Type Annotations さまざまな型注釈

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use. あなたは、あなたが定数または変数を宣言するとき、その定数または変数が格納することができる値の種類について明確にするために、型注釈を提供することができます。定数か変数の名前のあとにコロンを置いて、1つの空白に続き、使用する型の名前を続けることによって型注釈を書いてください。

This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values: この例は、welcomeMessageと呼ばれる変数に対して、その変数はString値を格納できることを示すために型注釈を提供します:

  1. var welcomeMessage: String

The colon in the declaration means “…of type…,” so the code above can be read as: 宣言でのコロンは「…の型の…」を意味します、それで上のコードは次のように読まれることができます:

“Declare a variable called welcomeMessage that’s of type String.” welcomeMessageと呼ばれる型Stringの変数を宣言する。」

The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored. フレーズ「型Stringの」は、「どんなString値でも格納することができる」ことを意味します。それを、格納されることができる「物の型」(または「物の種類」)の意味と思ってください。

The welcomeMessage variable can now be set to any string value without error: welcomeMessage変数は、現在エラーなしでどんな文字列値にでも設定されることができます:

  1. welcomeMessage = "Hello"

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name: あなたは同じ型の複数の関連した変数を、1行上に、コンマで区切って、型注釈を1つだけ最後の変数名の後につけて、定義することができます。

  1. var red, green, blue: Double

Note 注意

It’s rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it’s defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value. あなたが型注釈を書く必要があることは実際問題として、まれです。あなたが最初の値を定数または変数に、それが定義される時点で提供するならば、スウィフトはたいていその定数または変数のために使われる型を推測することが、「型安全と型推論」で記述されるように可能です。上のwelcomeMessageの例では、初期値が提供されません、それでwelcomeMessage変数の型は、最初の値から推論されるのではなく、型注釈で指定されます。

Naming Constants and Variables 定数と変数に名をつける

Constant and variable names can contain almost any character, including Unicode characters: 定数と変数の名前は、ユニコード文字を含めて、ほとんどどんな文字でも含むことができます:

  1. let π = 3.14159
  2. let 你好 = "你好世界"
  3. let 🐶🐮 = "dogcow"

Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use Unicode scalar values, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name. 定数と変数の名前は、空白文字、数学記号、矢印、私的使用Unicodeスカラー値、または罫線文字を含むことができません。そしてそれらは数字から始まることもできません、けれども数字が名前内のどこか他で含まれることはできます。

Once you’ve declared a constant or variable of a certain type, you can’t declare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant. 一旦あなたが特定の型のある定数または変数を宣言してしまったならば、あなたは同じ名前でもう一度それを宣言し直すこと、またはそれを異なる型の値を格納するように変更することは出来ません。そして、あなたはある定数を変数に、またはある変数を定数に変更することもできません。

Note 注意

If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with backticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice. あなたが予約済みのスウィフトのキーワードと同じ名前を定数または変数に与える必要があるならば、名前としてそれを使うときバッククォート(`)でそのキーワードを囲んでください。しかし、あなたに選択が全くない場合を除き、キーワードをなんらかの名前として使用することを避けてください。

You can change the value of an existing variable to another value of a compatible type. In this example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!": あなたは、既存の変数の値を、別の互換性を持つ型の値に変えることができます。この例では、friendlyWelcomeの値は、"Hello!"から"Bonjour!"に変えられます:

  1. var friendlyWelcome = "Hello!"
  2. friendlyWelcome = "Bonjour!"
  3. // friendlyWelcome is now "Bonjour!"(friendlyWelcomeは、現在「Bonjour!」です)

Unlike a variable, the value of a constant can’t be changed after it’s set. Attempting to do so is reported as an error when your code is compiled: 変数とは異なり、それが設定された後で定数の値は変更できません。そうしようとすることは、あなたのコードがコンパイルされる時にエラーとして報告されます:

  1. let languageName = "Swift"
  2. languageName = "Swift++"
  3. // This is a compile-time error: languageName cannot be changed.(これはコンパイル時エラーです:anguageNameは変わることができません。)

Printing Constants and Variables 定数と変数を出力する

You can print the current value of a constant or variable with the print(_:separator:terminator:) function: あなたは、print(_:separator:terminator:)関数で定数または変数の現在の値を出力することができます:

  1. print(friendlyWelcome)
  2. // Prints "Bonjour!"(「Bonjour!」を出力します)

The print(_:separator:terminator:) function is a global function that prints one or more values to an appropriate output. In Xcode, for example, the print(_:separator:terminator:) function prints its output in Xcode’s “console” pane. The separator and terminator parameter have default values, so you can omit them when you call this function. By default, the function terminates the line it prints by adding a line break. To print a value without a line break after it, pass an empty string as the terminator—for example, print(someValue, terminator: ""). For information about parameters with default values, see Default Parameter Values. print(_:separator:terminator:)関数は、ひとつ以上の値を適切な出力先に出力するグローバルな関数です。例えば、Xcodeでは、print(_:separator:terminator:)関数はその出力をXcodeの「コンソール」枠に表示します。separatorterminatorパラメータは省略時の値を持ちます、それであなたはそれらを省略することが、この関数をあなたが呼び出す時に可能です。初期状態では、この関数はそれが出力する行を改行を加えて終わります。ある値をそれの後に改行なしで出力するには、空の文字列を終端子(ターミネータ)として渡してください ― 例えば、print(someValue, terminator: "")。省略時の値を持つパラメータについての情報として、省略時のパラメータ値を見てください。

Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis: スウィフトは、定数または変数の名前をより長い文字列の中にプレースホルダーとして含めるために、そしてそれをその定数または変数の現在の値と取り替えることをスウィフトに促すために、文字列補間を使います。丸括弧にその名前を包んで、始めの括弧の前のバックスラッシュでそれをエスケープします:

  1. print("The current value of friendlyWelcome is \(friendlyWelcome)")
  2. // Prints "The current value of friendlyWelcome is Bonjour!"(「The current value of friendlyWelcome is Bonjour!」を出力します)

Note 注意

All options you can use with string interpolation are described in String Interpolation. あなたが文字列補間で使うことができるオプション全ては、「文字列補間」で記述されます。

Comments コメント

Use comments to include nonexecutable text in your code, as a note or reminder to yourself. Comments are ignored by the Swift compiler when your code is compiled. あなた自身への注意事項または覚え書きとして、実行可能でないテキストをあなたのコードに含めるために、コメントを使ってください。あなたのコードがコンパイルされるとき、コメントはスウィフトのコンパイラによって無視されます。

Comments in Swift are very similar to comments in C. Single-line comments begin with two forward-slashes (//): スウィフトのコメントは、Cのコメントに非常に似ています。一行コメントは2つのスラッシュで始まります(//):

  1. // This is a comment.(これはコメントです。)

Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/): 複数行コメントは、スラッシュに続く星印(/*)で始まり、星印に続くスラッシュ(*/)で終わります:

  1. /* This is also a comment (これもコメントです)
  2. but is written over multiple lines.(しかし複数行にわたって書かれます。) */

Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block: Cでの複数行コメントと違って、スウィフトの複数行コメントは他の複数行コメント内部に入れ子にされることができます。あなたはひとつの複数行コメント・ブロックを始めて、それから第二の複数行を最初のブロック以内に始めることによって入れ子にされたコメントを書きます。第二のブロックはそれから閉じられます、そして最初のブロックが続きます:

  1. /* This is the start of the first multiline comment. (最初の複数行コメントの始まり。)
  2. /*This is the second, nested multiline comment.(第二の入れ子の複数行コメント。) */
  3. This is the end of the first multiline comment.(最初の複数行コメントの終わり。) */

Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments. 入れ子にされた複数行コメントによって、たとえコードがすでに複数行コメントを含むとしても、あなたは速く簡単にコードの大きなブロックをコメントアウトすることが可能になります。

Semicolons セミコロン

Unlike many other languages, Swift doesn’t require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line: 多くの他の言語とは異なり、スウィフトはあなたにあなたのコードにおいて各文の後にセミコロン(;)を書くことを要求しません、けれどもあなたが望むならば、あなたはそうできます。それにもかかわらず、セミコロンは必要とされます、もしあなたが1つの行に複数の別々の文を書きたい場合には:

  1. let cat = "🐱"; print(cat)
  2. // Prints "🐱"

Integers 整数

Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). 整数は、小数部分のない数すべてです、例えば42-23など。整数は、符号つき(正、ゼロ、または負)または符号なし(正またはゼロ)のどちらかです。

Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names. スウィフトは、8、16、32、そして64ビット形式で、符号つきおよび符号なし整数を提供します。これらの整数は、8ビットの符号なし整数が型UInt8である、そして32ビットの符号つき整数が型Int32であるという点で、Cに似ている命名規則に従います。スウィフトにおける全ての型のように、これらの整数型は頭文字を使った名前を持ちます。

Integer Bounds 整数の限界

You can access the minimum and maximum values of each integer type with its min and max properties: あなたは、そのminmaxプロパティで各整数型の最小と最大の値を得ることができます:

  1. let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8(minValuesは0に等しく、そしてUInt8型です)
  2. let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8(maxValuesは255に等しく、そしてUInt8型です)

The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type. これらのプロパティの値は、適切なサイズの数の型(例えば上の例でのUInt8)であり、したがって、式の中で同じ型の他の値と並べて使われることができます。

Int

In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size: ほとんどの場合、あなたはあなたのコードにおいて使用するのに整数の特定のサイズを選択する必要はありません。スウィフトは追加の整数型、Intを提供します、そしてそれは、現在のプラットホーム固有のワードサイズと同じ大きさを持ちます:

  • On a 32-bit platform, Int is the same size as Int32. 32ビットのプラットホーム上で、IntInt32と同じサイズです。
  • On a 64-bit platform, Int is the same size as Int64. 64ビットのプラットホーム上で、IntInt64と同じサイズです。

Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges. あなたが整数の特定のサイズを扱う必要がない限り、常に、あなたのコードの整数値のためにIntを使ってください。これは、コードの整合性と相互運用性を支援します。32ビットのプラットホーム上でさえ、Int-2,147,483,6482,147,483,647の間のどんな値でも格納することができ、多くの整数範囲のために十分に大きいです。

UInt 符号なし整数(Unsigned Integer)

Swift also provides an unsigned integer type, UInt, which has the same size as the current platform’s native word size: スウィフトはまた、符号なし整数型、UIntを提供します、そしてそれは、現在のプラットホーム固有のワードサイズと同じ大きさを持ちます:

  • On a 32-bit platform, UInt is the same size as UInt32. 32ビットのプラットホーム上で、UIntUInt32と同じサイズです。
  • On a 64-bit platform, UInt is the same size as UInt64. 64ビットのプラットホーム上で、UIntUInt64と同じサイズです。

Note 注意

Use UInt only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this isn’t the case, Int is preferred, even when the values to be stored are known to be nonnegative. A consistent use of Int for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in Type Safety and Type Inference. あなたが特にプラットホーム固有のワードサイズと同じ大きさで符号なし整数型を必要とする時にだけUIntを使ってください。この場合でないならば、保存される値が負数でないことがわかっている時でさえ、Intがむしろ好まれます。整数値のためのIntの一貫した使用は、コードの相互運用性を支援して、異なる数の型の間で変換する必要を避けて、「型安全と型推論」で記述されるように、整数型推論に合致します。

Floating-Point Numbers 浮動小数点数

Floating-point numbers are numbers with a fractional component, such as 3.14159, 0.1, and -273.15. 浮動小数点数は小数部を持つ数です、例えば3.141590.1、そして-273.15など。

Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types: 浮動小数点型は、整数型よりずっと広い値の幅を表すことができ、そしてIntに格納できるよりずっと大きいまたは小さい数を格納できます。スウィフトは、2つの符号つき浮動小数点数型を提供します:

  • Double represents a 64-bit floating-point number. Doubleは、64ビットの浮動小数点数を表します。
  • Float represents a 32-bit floating-point number. Floatは、32ビットの浮動小数点数を表します。

Note 注意

Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred. Doubleは少なくとも10進数で15桁の精度を持ちます、一方でFloatの精度は10進数で6桁ほどです。使うのに適切な浮動小数点型は、あなたのコードにおいて扱わなければならない値の種別と幅に依ります。どちらの型でも適切である状況では、Doubleが望ましいです。

Type Safety and Type Inference 型安全と型推論

Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code requires a String, you can’t pass it an Int by mistake. スウィフトは、型安全な言語です。型安全な言語は、あなたのコードが扱うことができる値の型について、あなたが確信を持つように促します。あなたのコードの一部がStringを要求するならば、あなたは誤ってそれにIntを渡すことはできません。

Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process. スウィフトが型安全であるので、それは、あなたのコードをコンパイルするとき型チェックを実行して、あらゆる組合せを誤った型をエラーとして合図します。これは、あなたに開発過程においてエラーをできるだけ早く捕えて修復するのを可能にします。

Type-checking helps you avoid errors when you’re working with different types of values. However, this doesn’t mean that you have to specify the type of every constant and variable that you declare. If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. 型をチェックすることは、あなたが異なる種類の値を扱っているとき、あなたがエラーを避ける手助けをします。しかし、これはあなたがすべてのあなたが宣言する定数と変数の型を指定しなければならないことを意味しません。あなたが必要とする値の型をあなたが指定しないならば、スウィフトは適切な型を導きだすために型推論を使います。型推論は、コンパイラに自動的に特定の式の型を演繹することを、それがあなたのコードをコンパイルする時に、単純にあなたが提供する値を調べることによって、可能にします。

Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C. Constants and variables are still explicitly typed, but much of the work of specifying their type is done for you. 型推論のため、スウィフトはCまたはObjective-Cのような言語よりはるかに少ない型宣言しか必要としません。定数と変数は依然として明確に型を決められます、しかしそれらの型を指定する行為のほとんどは、あなたのために行われます。

Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as 42 and 3.14159 in the examples below.) あなたが最初の値で定数または変数を宣言するとき、型推論は特に役に立ちます。これは、リテラル値(またはリテラル)を定数または変数に、あなたがそれを宣言する時点で代入することによって、しばしば行われます。(リテラル値「文字通りの値」は、直接あなたのソース・コードで見かける値です、例えば下の例での423.14159)。

For example, if you assign a literal value of 42 to a new constant without saying what type it is, Swift infers that you want the constant to be an Int, because you have initialized it with a number that looks like an integer: 例えば、あなたがそれがどんな型であるかについて言うことなく、新しい定数にリテラル値42を代入するならば、スウィフトは、あなたがその定数にIntであって欲しいのだと推測します、なぜならあなたがそれを整数のように見える数で初期化したからです:

  1. let meaningOfLife = 42
  2. // meaningOfLife is inferred to be of type Int(meaningOfLifeはInt型であると推測されます)

Likewise, if you don’t specify a type for a floating-point literal, Swift infers that you want to create a Double: 同様に、あなたがある浮動小数点リテラルのために型を指定しないならば、スウィフトはあなたがDoubleをつくりたいと推測します:

  1. let pi = 3.14159
  2. // pi is inferred to be of type Double(パイはDouble型であると推測されます)

Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers. 浮動小数点数の型を推論するとき、スウィフトは常にDoubleを選びます(Floatではなく)。

If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context: あなたがある式の中で整数と浮動小数点リテラルを結合するならば、その前後関係からDoubleの型が推論されます:

  1. let anotherPi = 3 + 0.14159
  2. // anotherPi is also inferred to be of type Double(anotherPiもまたDouble型であると推論されます)

The literal value of 3 has no explicit type in and of itself, and so an appropriate output type of Double is inferred from the presence of a floating-point literal as part of the addition. リテラル値3は明確な型をそれ自体は持ちません、それで適切な出力のDouble型は、加算部分の浮動小数点リテラルの存在から推論されます。

Numeric Literals 数のリテラル

Integer literals can be written as: 整数リテラルは、次のように書かれることができます:

  • A decimal number, with no prefix 10進数は、接頭辞なしで
  • A binary number, with a 0b prefix 2進数は、接頭辞0bつきで
  • An octal number, with a 0o prefix 8進数は、接頭辞0oつきで
  • A hexadecimal number, with a 0x prefix 16進数は、接頭辞0xつきで

All of these integer literals have a decimal value of 17: 次の整数リテラルの全ては、10進の値で17を持ちます:

  1. let decimalInteger = 17
  2. let binaryInteger = 0b10001 // 17 in binary notation(2進法での17)
  3. let octalInteger = 0o21 // 17 in octal notation(8進法での17)
  4. let hexadecimalInteger = 0x11 // 17 in hexadecimal notation(16進法での17)

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix). They must always have a number (or hexadecimal number) on both sides of the decimal point. Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e; hexadecimal floats must have an exponent, indicated by an uppercase or lowercase p. 浮動小数点リテラルは、10進(接頭辞なし)、または16進(接頭辞0xつき)であることができます。それらは、常に小数点の両側で数(または16進の数)を持たなければなりません。10進浮動小数点はまた、任意に指数を持つことができ、大文字か小文字のeで示されます;16進浮動小数点は、指数を持つ必要があり、大文字か小文字のpで示されます。

For decimal numbers with an exponent of exp, the base number is multiplied by 10exp: expの指数を持つある10進数に対して、その基数は10expを掛けられます:

  • 1.25e2 means 1.25 x 102, or 125.0. 1.25e2は、1.25 × 102、または125.0を意味します。
  • 1.25e-2 means 1.25 x 10-2, or 0.0125. 1.25e-2は、1.25 × 10-2、または0.0125を意味します。

For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp: expの指数を持つある16進数に対して、その基数は2expを掛けられます:

  • 0xFp2 means 15 x 22, or 60.0. 0xFp2は、15 × 22、または60.0を意味します。
  • 0xFp-2 means 15 x 2-2, or 3.75. 0xFp-2は、15 × 2-2、または3.75を意味します。

All of these floating-point literals have a decimal value of 12.1875: 以下の浮動小数点リテラルの全ては、10進の値で12.1875を持ちます:

  1. let decimalDouble = 12.1875
  2. let exponentDouble = 1.21875e1
  3. let hexadecimalDouble = 0xC.3p0

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeros and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal: 数のリテラルは、それらをより簡単に読めるように書式を整える追加のものを含むことができます。整数と浮動小数点は、余分のゼロを詰められることができ、読みやすくするためにアンダースコアを含むことができます。書式整形のどちらの種類も、もととなるリテラルの値に影響を及ぼしません:

  1. let paddedDouble = 000123.456
  2. let oneMillion = 1_000_000
  3. let justOverOneMillion = 1_000_000.000_000_1

Numeric Type Conversion 数の型変換

Use the Int type for all general-purpose integer constants and variables in your code, even if they’re known to be nonnegative. Using the default integer type in everyday situations means that integer constants and variables are immediately interoperable in your code and will match the inferred type for integer literal values. Int型を全ての一般的な目的のための整数の定数と変数に対してあなたのコードにおいて使ってください、たとえそれらが負数でないことが知られているとしてもです。日々の状況において初期状態として整数型を使うことは、整数の定数と変数があなたのコードにおいて直接に情報交換が可能で、いろいろな整数のリテラル値に対して推論される型と調和することを意味します。

Use other integer types only when they’re specifically needed for the task at hand, because of explicitly sized data from an external source, or for performance, memory usage, or other necessary optimization. Using explicitly sized types in these situations helps to catch any accidental value overflows and implicitly documents the nature of the data being used. 外部ソース由来の明確に大きさを設定されたデータのために、またはパフォーマンス、メモリ使用、または他の必要な最適化のためになど、目下の作業に特に必要とされる時にだけ、他の整数を使ってください。これらの状況において明示的に大きさを設定された型を使うことは、偶発的な何らかの値のオーバフローを捕えることや、使われているデータの性質を暗黙的に記録することの手助けになります。

Integer Conversion 整数変換

The range of numbers that can be stored in an integer constant or variable is different for each numeric type. An Int8 constant or variable can store numbers between -128 and 127, whereas a UInt8 constant or variable can store numbers between 0 and 255. A number that won’t fit into a constant or variable of a sized integer type is reported as an error when your code is compiled: 整数の定数または変数に格納されることができる数の範囲は、それぞれの数の型で異なります。Int8定数または変数は、-128127の間の数を格納することができる一方、UInt8定数または変数は、0255の間の数を格納することができます。あなたのコードがコンパイルされるとき、ある大きさを設定された整数型の定数または変数に収まらない数はエラーとして報告されます:

  1. let cannotBeNegative: UInt8 = -1
  2. // UInt8 can't store negative numbers, and so this will report an error(UInt8は負の数を格納することができません、それでこれはエラーを報告します)
  3. let tooBig: Int8 = Int8.max + 1
  4. // Int8 can't store a number larger than its maximum value,(Int8はその最大の値より大きい数を格納することができません)
  5. // and so this will also report an error(それでこれも同様にエラーを報告します)

Because each numeric type can store a different range of values, you must opt in to numeric type conversion on a case-by-case basis. This opt-in approach prevents hidden conversion errors and helps make type conversion intentions explicit in your code. それぞれの数の型は、値の異なる幅を格納できるので、あなたは数の型変換を一件一件を原則に決めていかなければなりません。このオプトインの(個々に決めていく)取り組み方は、隠された変換エラーを防いで、あなたのコードにおいて型変換の意図を明確にするのを助けます。

To convert one specific number type to another, you initialize a new number of the desired type with the existing value. In the example below, the constant twoThousand is of type UInt16, whereas the constant one is of type UInt8. They can’t be added together directly, because they’re not of the same type. Instead, this example calls UInt16(one) to create a new UInt16 initialized with the value of one, and uses this value in place of the original: 1つの特定の数の型を他のものに変換するために、あなたは望む型の新しい数を既存の値で初期化します。下記の例で、定数twoThousand型UInt16ですが、定数oneは型UInt8です。それらは直接にひとつに加算されることができません、それらが同じ型でないためです。その代わりに、この例はoneの値で初期化される新しいUInt16を作るためにUInt16(one)を呼んで、オリジナルの代わりにこの値を使います:

  1. let twoThousand: UInt16 = 2_000
  2. let one: UInt8 = 1
  3. let twoThousandAndOne = twoThousand + UInt16(one)

Because both sides of the addition are now of type UInt16, the addition is allowed. The output constant (twoThousandAndOne) is inferred to be of type UInt16, because it’s the sum of two UInt16 values. 加算の両側が今では型UInt16であるので、加算は許されます。出力された定数(twoThousandAndOne)は、型UInt16であると推測されます、それが2つのUInt16値の合計であるので。

SomeType(ofInitialValue) is the default way to call the initializer of a Swift type and pass in an initial value. Behind the scenes, UInt16 has an initializer that accepts a UInt8 value, and so this initializer is used to make a new UInt16 from an existing UInt8. You can’t pass in any type here, however—it has to be a type for which UInt16 provides an initializer. Extending existing types to provide initializers that accept new types (including your own type definitions) is covered in Extensions. SomeType(ofInitialValue)は、あるスウィフト型のイニシャライザを呼んで、初期値を渡すために通常使う方法です。舞台裏で、UInt16UInt8値を受け入れるイニシャライザを持ちます、それでこのイニシャライザが新しいUInt16を既存のUInt8から作るために使われます。しかしながら、あなたはあらゆる型をここに渡すことはできません ― それはUInt16がイニシャライザを提供する型でなければなりません。新しい型(あなた独自の型定義を含む)を受け入れるイニシャライザを提供するように既存の型を拡張することは、「拡張」で扱われます。

Integer and Floating-Point Conversion 整数と浮動小数点の変換

Conversions between integer and floating-point numeric types must be made explicit: 整数と浮動小数点数型の間の変換は、明示的に行われる必要があります:

  1. let three = 3
  2. let pointOneFourOneFiveNine = 0.14159
  3. let pi = Double(three) + pointOneFourOneFiveNine
  4. // pi equals 3.14159, and is inferred to be of type Double(piは、3.14159に等しく、型Doubleであると推論されます)

Here, the value of the constant three is used to create a new value of type Double, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed. ここでは、定数threeの値が、Double型の新しい値をつくるために使われます、それでこの加算の両側は同じ型です。適切なこの変換なしでは、この加算は許されません。

Floating-point to integer conversion must also be made explicit. An integer type can be initialized with a Double or Float value: 浮動小数点を整数に変換することは、また、明示的に行われる必要があります。整数型は、DoubleまたはFloat値で初期化されることができます:

  1. let integerPi = Int(pi)
  2. // integerPi equals 3, and is inferred to be of type Int(integerPiは、3に等しく、型Intであると推測されます)

Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3. この方法で新しい整数値を初期化するとき、浮動小数点値は常に切り詰められます。これは、4.754に、そして-3.9-3になることを意味します。

Note 注意

The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals don’t have an explicit type in and of themselves. Their type is inferred only at the point that they’re evaluated by the compiler. 数の定数や変数を結合することに対する規則は、数のリテラルに対する規則と異なります。リテラル値3は、直接にリテラル値0.14159に加えられることができます、なぜなら数リテラルがそれら自身において明確な型を持たないためです。それらの型は、それらがコンパイラによって評価される時点においてのみ、推論されます。

Type Aliases 型エイリアス

Type aliases define an alternative name for an existing type. You define type aliases with the typealias keyword. 型エイリアスは、既存の型の代替の名前を定義します。あなたは、typealiasキーワードで型エイリアスを定義します。

Type aliases are useful when you want to refer to an existing type by a name that’s contextually more appropriate, such as when working with data of a specific size from an external source: 型エイリアスは、あなたがより文脈上適切な名前で既存の型に言及したいとき役に立ちます、たとえば外部ソースからの特定の大きさのデータを扱う時など:

  1. typealias AudioSample = UInt16

Once you define a type alias, you can use the alias anywhere you might use the original name: 一旦あなたがある型エイリアスを定義するならば、あなたが本来の名前を使うであろうどこにでも、あなたはそのエイリアスを使用することができます:

  1. var maxAmplitudeFound = AudioSample.min
  2. // maxAmplitudeFound is now 0(maxAmplitudeFoundは、現在0です)

Here, AudioSample is defined as an alias for UInt16. Because it’s an alias, the call to AudioSample.min actually calls UInt16.min, which provides an initial value of 0 for the maxAmplitudeFound variable. ここでは、AudioSampleUInt16に対するエイリアス(別名)として定義されます。それがエイリアスであるので、AudioSample.minへの呼び出しは実際にはUInt16.minを呼び、それは0の初期値をmaxAmplitudeFound変数のために提供します。

Booleans ブール

Swift has a basic Boolean type, called Bool. Boolean values are referred to as logical, because they can only ever be true or false. Swift provides two Boolean constant values, true and false: スウィフトは、ひとつの基本的なブール型を持ちます、それはBoolと呼ばれるものです。ブールの値は、論理として参照されます、なぜならそれらは真か偽であることだけができるからです。スウィフトは2つのブールの定数値、truefalseを提供します:

  1. let orangesAreOrange = true
  2. let turnipsAreDelicious = false

The types of orangesAreOrange and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values. As with Int and Double above, you don’t need to declare constants or variables as Bool if you set them to true or false as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known. orangesAreOrangeturnipsAreDeliciousの型は、それらがブールのリテラル値で初期化されたという事実から、Boolとして推論されます。上のIntDoubleと同様に、あなたがそれらを作成するやいなやtrueまたはfalseに設定するならば、あなたは定数または変数をBoolとして宣言する必要はありません。型推論は、スウィフトのコードを、それが定数または変数を型がすでに知られている他の値で初期化するとき、より簡潔で読みやすくするのを助けます。

Boolean values are particularly useful when you work with conditional statements such as the if statement: あなたがif文のような条件つきの文で作業するとき、ブールの値は特に役に立ちます:

  1. if turnipsAreDelicious {
  2. print("Mmm, tasty turnips!")
  3. } else {
  4. print("Eww, turnips are horrible.")
  5. }
  6. // Prints "Eww, turnips are horrible."(「うー、カブ怖い。」を出力します)

Conditional statements such as the if statement are covered in more detail in Control Flow. if文のような条件つきの文は、更に詳細に「制御の流れ」で扱われます。

Swift’s type safety prevents non-Boolean values from being substituted for Bool. The following example reports a compile-time error: スウィフトの型安全は、非ブール値がBoolの代用にされるのを妨げます。以下の例は、コンパイル時エラーを報告します:

  1. let i = 1
  2. if i {
  3. // this example will not compile, and will report an error(この例はコンパイルせず、エラーを報告します)
  4. }

However, the alternative example below is valid: しかし、これに代わる以下の例は有効です:

  1. let i = 1
  2. if i == 1 {
  3. // this example will compile successfully(この例は、うまくコンパイルします)
  4. }

The result of the i == 1 comparison is of type Bool, and so this second example passes the type-check. Comparisons like i == 1 are discussed in Basic Operators. i == 1の比較の結果は型Boolです、それでこの第二の例は型チェックを通ります。i == 1のような比較は「基本の演算子」で議論されます。

As with other examples of type safety in Swift, this approach avoids accidental errors and ensures that the intention of a particular section of code is always clear. スウィフトにおける型安全に関する他の例と同様に、このやり方は、偶然のエラーを避けること、そしてコードの特定の節の意図を常にはっきりさせることを確実にします。

Tuples タプル

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other. タプルは、複数の値を1つの複合値にまとめます。タプルの内部の値は、どんな型でもかまいません、そして互いに同じ型である必要はありません。

In this example, (404, "Not Found") is a tuple that describes an HTTP status code. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of 404 Not Found is returned if you request a webpage that doesn’t exist. この例では、(404, "Not Found")がひとつのタプルです、それはHTTP状態コードを記述します。HTTP状態コードは、あなたがウェブ・ページを要請するときはいつでもウェブ・サーバーによって返されるある特別な値です。状態コード404 Not Foundは、あなたが存在しないウェブ・ページを要請するならば返されます。

  1. let http404Error = (404, "Not Found")
  2. // http404Error is of type (Int, String), and equals (404, "Not Found")(http404Errorは、型が(Int, String)です、そして(404, "Not Found")と等しいです)

The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type (Int, String)”. この(404, "Not Found")タプルはIntStringをひとつにまとめて、HTTP状態コードに2つの別々の値:数と人間の読める説明を与えます。それは型(Int, String)のタプルとして記述されることができます。

You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require. あなたは、いろいろな型をどんな順列にしてタプルを作っても構いません、そして、それらはあなたが望むだけ多くの異なる型を含むことができます。あなたが(Int, Int, Int)の型のタプル、または(String, Bool)、またはあなたが実際に必要とするあらゆる他の順列を持つのを止めるものは何もありません。

You can decompose a tuple’s contents into separate constants or variables, which you then access as usual: あなたはタプルの内容を個々の定数または変数に分解することができます。そして、あなたはそれから通常通りそれにアクセスします:

  1. let (statusCode, statusMessage) = http404Error
  2. print("The status code is \(statusCode)")
  3. // Prints "The status code is 404"(「状態コードは404です」を出力します)
  4. print("The status message is \(statusMessage)")
  5. // Prints "The status message is Not Found"(「状態メッセージが見つかりません」を出力します)

If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple: あなたがタプルの値の一部を必要とするだけならば、あなたがタプルを分解するとき、アンダースコア(_)で、タプルの一部を無視してください:

  1. let (justTheStatusCode, _) = http404Error
  2. print("The status code is \(justTheStatusCode)")
  3. // Prints "The status code is 404"(「状態コードは404です」を出力します)

Alternatively, access the individual element values in a tuple using index numbers starting at zero: あるいは、ゼロから始まっているインデックス番号を使ってタプルの個々の要素の値にアクセスしてください:

  1. print("The status code is \(http404Error.0)")
  2. // Prints "The status code is 404"(「状態コードは404です」を出力します)
  3. print("The status message is \(http404Error.1)")
  4. // Prints "The status message is Not Found"(「状態メッセージが見つかりません」を出力します)

You can name the individual elements in a tuple when the tuple is defined: あなたは、タプルの個々の要素に名前をつけることが、そのタプルが定義される時に可能です:

  1. let http200Status = (statusCode: 200, description: "OK")

If you name the elements in a tuple, you can use the element names to access the values of those elements: あなたがタプルの要素に名をつけるならば、あなたはそれらの要素の値にアクセスするために要素名を使用することができます:

  1. print("The status code is \(http200Status.statusCode)")
  2. // Prints "The status code is 200"(「状態コードは200です」を出力します)
  3. print("The status message is \(http200Status.description)")
  4. // Prints "The status message is OK"(「状態メッセージはOKです」を出力します)

Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. For more information, see Functions with Multiple Return Values. タプルは、特に関数の戻り値として便利です。ウェブ・ページを探してくるある関数は、ページ検索の成功または失敗を記述するために(Int, String)のタプル型を返すかもしれません。2つの別の値をそれぞれ異なる型で持つひとつのタプルを返すことによって、その関数は、それが1つの型の1つの値を返すことができるだけよりも、その結果に関するより役に立つ情報を提供します。詳細は、「複数の戻り値をもつ関数」を見てください。

Note 注意

Tuples are useful for simple groups of related values. They’re not suited to the creation of complex data structures. If your data structure is likely to be more complex, model it as a class or structure, rather than as a tuple. For more information, see Structures and Classes. タプルは、関連した値の単純なグループに対して便利です。それらは、複雑なデータ構造物の作成には適していません。あなたのデータ構造体がより複雑になるようならば、それをクラスまたは構造体として形作ってください、タプルとしてよりも。詳細は、クラスと構造体を見てください。

Optionals オプショナル

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all. あなたはオプショナルを、ある値が不在かもしれない状況において使います。あるオプショナルは2つの可能性を表します:ある値が存在する、するとあなたはそのオプショナルをアンラップすることでその値を利用できます、または値がそもそも存在しないかのいずれか。

Note 注意

The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” However, this only works for objects—it doesn’t work for structures, basic C types, or enumeration values. For these types, Objective-C methods typically return a special value (such as NSNotFound) to indicate the absence of a value. This approach assumes that the method’s caller knows there’s a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for any type at all, without the need for special constants. オプショナルの概念は、CまたはObjective-Cの中に存在しません。Objective-Cにおいて最も近いものは、オブジェクトを返すメソッドからそうできない場合にnilを返す能力です、そのときnilは「有効なオブジェクトの欠如」を意味しています。しかし、それは単にオブジェクトのためだけに働きます ― それは構造体、基本的なC型、または列挙値のために働きません。これらの型のために、Objective-Cメソッドは、値の欠如を示すために概して特別な値(例えばNSNotFound)を返します。このアプローチは、メソッドの呼び出し側が試験するべき特別な値があるのを知っていて、それについて調べるのを忘れないでいると仮定します。スウィフトのオプショナルは、あなたに特別な定数の必要なしにあらゆる全ての型の値の欠如を示させます。

Here’s an example of how optionals can be used to cope with the absence of a value. Swift’s Int type has an initializer which tries to convert a String value into an Int value. However, not every string can be converted into an integer. The string "123" can be converted into the numeric value 123, but the string "hello, world" doesn’t have an obvious numeric value to convert to. ここに、値の欠如に対処するためにどのようにオプショナルが使われることができるかの1つの例があります。スウィフトのInt型はあるイニシャライザを持ちます、それはString値をInt値に変換することを試みます。しかし、すべての文字列が、整数に変えられることができるというわけでありません。文字列"123"は数の値123に変えられることができます、しかし文字列"hello, world"には変えるための明らかな数の値がありません。

The example below uses the initializer to try to convert a String into an Int: 下の例は、このイニシャライザを使用してStringIntに変えることを試みます:

  1. let possibleNumber = "123"
  2. let convertedNumber = Int(possibleNumber)
  3. // convertedNumber is inferred to be of type "Int?", or "optional Int"(convertedNumberは、型「Int?」または「オプショナルのInt」であると推論されます)

Because the initializer might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.) このイニシャライザが失敗するかもしれないので、それはIntではなくて、オプショナルIntを返します。オプショナルのIntは、Int?のように書かれます、Intではなく。疑問符はそれが含む値がオプショナルであることを示します、そしてそれが何かの Int値を含むかもしれない、あるいはそれがまったく値を含まないかもしれないことを意味しています。 (それは、他の何か、例えばBool値またはString値などを含むことはできません。それはひとつのInt、またはそれは全く何も無いかのどちらかです。)

nil

You set an optional variable to a valueless state by assigning it the special value nil: あなたが、あるオプショナルの変数を値が無い状態へと設定するには、それに特別な値nilを代入します:

  1. var serverResponseCode: Int? = 404
  2. // serverResponseCode contains an actual Int value of 404(serverResponseCodeは、実際にあるInt値404を含みます)
  3. serverResponseCode = nil
  4. // serverResponseCode now contains no value(serverResponseCodeは、現在は値を含みません)

Note 注意

You can’t use nil with non-optional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type. あなたは、nilを非オプショナルの定数および変数で使うことができます。あなたのコードの中の定数または変数が特定の条件下で値の欠如を取り扱う必要があるならば、常に、それを適切な型のオプショナルの値として宣言してください。

If you define an optional variable without providing a default value, the variable is automatically set to nil for you: あなたが既定値を提供することなくオプショナルの変数を定義するならば、その変数はあなたのために自動的にnilに設定されます:

  1. var surveyAnswer: String?
  2. // surveyAnswer is automatically set to nil(surveyAnswerは、自動的にnilに設定されます)

Note 注意

Swift’s nil isn’t the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil isn’t a pointer—it’s the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types. スウィフトのnilは、Objective-Cでのnilと同じものではありません。Objective-Cでは、nilは、ある存在しないオブジェクトへのポインターです。スウィフトでは、nilはポインターではありません ― それは、ある特定の型のある値の不在です。すべての型のオプショナルが、nilに設定されることができます、単にオブジェクト型だけでなく。

If Statements and Forced Unwrapping if文と強制アンラップ

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=). あなたは、if文を、あるオプショナルが値を含むかどうか知るために使うことができます、それは、そのオプショナルをnilと比べることによって行います。あなたは、この比較を「同等」演算子(==)または「不等」演算子(!=)を使って実行します。

If an optional has a value, it’s considered to be “not equal to” nil: あるオプショナルが値を持つならば、それはnilと「同等でない」と判断されます:

  1. if convertedNumber != nil {
  2. print("convertedNumber contains some integer value.")
  3. }
  4. // Prints "convertedNumber contains some integer value."(「convertedNumberは、何らかの整数値を持ちます」を出力します)

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation point (!) to the end of the optional’s name. The exclamation point effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value: 一旦あなたがそのオプショナルが値を含んでいることを確かめたなら、あなたは感嘆符(!)をオプショナルの名前の終わりに加えることによって、それに内在する値にアクセスすることが可能です。感嘆符は、実際上こう言っています、「私はこのオプショナルが間違いなくひとつの値を持つことを知っています;どうぞそれを使ってください」。これは、そのオプショナルの所有する値の強制アンラップとして知られます:

  1. if convertedNumber != nil {
  2. print("convertedNumber has an integer value of \(convertedNumber!).")
  3. }
  4. // Prints "convertedNumber has an integer value of 123."(「convertedNumberは、整数値123を持ちます」を出力します)

For more about the if statement, see Control Flow. if文に関する詳細は、制御の流れを見てください。

Note 注意

Trying to use ! to access a nonexistent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. 存在しないオプショナルの値にアクセスするために!を使うことを試みることは、実行時エラーの引き金となります。必ずあるオプショナルがnilではない値を含むことを、それの値を強制アンラップする!を使う前に確かめてください。

Optional Binding オプショナルを束縛する(定数・変数と結び付ける)

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action. if and while statements are described in more detail in Control Flow. あなたは、あるオプショナルが値を含むかどうか知るために、そしてもしそうならば、その値を一時的な定数または変数として利用可能にするために、オプショナル束縛を使うことができます。オプショナル束縛は、ifwhile文と一緒に使用して、オプショナルの内部の値を確認すること、そしてその値を定数または変数に抽出することを、一回の動作で可能にします。ifおよびwhile文は更に詳細に「制御の流れ」で記述されます。

Write an optional binding for an if statement as follows: オプショナルの束縛をif文のために次のように書いてください:

  1. if let constantName = someOptional {
  2. statements
  3. }

You can rewrite the possibleNumber example from the Optionals section to use optional binding rather than forced unwrapping: あなたはオプショナル節のpossibleNumber例を、強制アンラップではなくて、オプショナル束縛を使うように書き直すことができます:

  1. if let actualNumber = Int(possibleNumber) {
  2. print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
  3. } else {
  4. print("The string \"\(possibleNumber)\" couldn't be converted to an integer")
  5. }
  6. // Prints "The string "123" has an integer value of 123"

This code can be read as: このコードは、次のように解釈されることができます:

“If the optional Int returned by Int(possibleNumber) contains a value, set a new constant called actualNumber to the value contained in the optional.” Int(possibleNumber)によって返されるオプショナルのIntが値を含むならば、ある新しい定数actualNumberをそのオプショナルに含まれる値に設定してください。」

If the conversion is successful, the actualNumber constant becomes available for use within the first branch of the if statement. It has already been initialized with the value contained within the optional, and so you don’t use the ! suffix to access its value. In this example, actualNumber is simply used to print the result of the conversion. 変換が成功しているならば、定数actualNumberは、if文の最初の分岐の内部での利用に役立てられます。それは、すでにオプショナルの内部に含まれる値で初期化されています、それであなたはそれの値にアクセスするために!接尾辞を使いません。この例では、actualNumberは単にその変換の結果を出力するために使われます。

You can use both constants and variables with optional binding. If you wanted to manipulate the value of actualNumber within the first branch of the if statement, you could write if var actualNumber instead, and the value contained within the optional would be made available as a variable rather than a constant. あなたは、定数と変数の両方をオプショナル束縛で使用できます。あなたがactualNumberの値をif文の最初の分岐内で取り扱うことを望むならば、あなたはif var actualNumberを代わりに書くことができたでしょう、そしてオプショナル内部に含まれる値は定数ではなく変数として利用可能にされたでしょう。

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent: あなたは、単一のif文の中に、コンマで区切ったオプショナル束縛とブール条件をあなたが必要とするだけ多く含めることができます。何れかのオプショナル束縛の中の値がnilであるか何かのブール条件の評価がfalseになるならば、if文の条件の全体がfalseであるとみなされます。以下のif文は同等です:

  1. if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
  2. print("\(firstNumber) < \(secondNumber) < 100")
  3. }
  4. // Prints "4 < 42 < 100"
  5. if let firstNumber = Int("4") {
  6. if let secondNumber = Int("42") {
  7. if firstNumber < secondNumber && secondNumber < 100 {
  8. print("\(firstNumber) < \(secondNumber) < 100")
  9. }
  10. }
  11. }
  12. // Prints "4 < 42 < 100"

Note 注意

Constants and variables created with optional binding in an if statement are available only within the body of the if statement. In contrast, the constants and variables created with a guard statement are available in the lines of code that follow the guard statement, as described in Early Exit. if文の中でオプショナル束縛を使って作成された定数と変数は、そのif文の本文の内部でのみ利用可能です。対照的に、guard文で作成された定数と変数は、そのguard文以降のコード行において利用可能です、早期退出において議論されるように。

Implicitly Unwrapped Optionals 暗黙的にアンラップされるオプショナル

As described above, optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist. 先に述べたように、オプショナルは、ある定数や変数が「値がない」状態でも許されることを示します。オプショナルは、値が存在しているかどうか見るために、if文を使って調べられることが出来ます、そしてオプショナルの持つ値にそれが存在するならばアクセスするために、オプショナル束縛を使って条件に応じてアンラップされることができます。

Sometimes it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed, because it can be safely assumed to have a value all of the time. 時々、プログラムの構造から、あるオプショナルが必ず値を持つことが、その値が最初に設定される結果として、はっきりしていることがあります。これらの場合には、オプショナルの値をそれがアクセスされるたびに確認してアンラップする必要を無くすことは役に立ちます、なぜならそれがいつでも値を持つと安全に仮定されることが出来るためです。

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation point (String!) rather than a question mark (String?) after the type that you want to make optional. Rather than placing an exclamation point after the optional’s name when you use it, you place an exclamation point after the optional’s type when you declare it. これらの種類のオプショナルは、暗黙的にアンラップされるオプショナルとして定義されます。あなたは暗黙的にアンラップされるオプショナルを、あなたがオプショナルを作りたい型の後に疑問符(String?)ではなく感嘆符(String!)を置くことによって記述します。あなたがそれを使う時にそのオプショナルのもつ名前の後に感嘆符を置くよりも、あなたがそれを宣言する時にそのオプショナルのもつ型の後に感嘆符を書きたいとあなたは思うでしょう。

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties. 暗黙的にアンラップされるオプショナルは、あるオプショナルの値が存在するのをそのオプショナルが最初に定義された直後に確かめられて、それ以降あらゆる所で存在するのを自信を持って仮定出来るようにされる場合に役に立ちます。スウィフトでの暗黙的にアンラップされるオプショナルの主要な利用法は、所有参照と暗黙的にアンラップされるオプショナルのプロパティで記述されるように、クラス初期化の間にあります。

An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a non-optional value, without the need to unwrap the optional value each time it’s accessed. The following example shows the difference in behavior between an optional string and an implicitly unwrapped optional string when accessing their wrapped value as an explicit String: 暗黙的にアンラップされるオプショナルは、舞台裏では普通のオプショナルです、しかしまたオプショナルでない値のように扱うこともできます、それがアクセスされるたびにオプショナルの値をアンラップする必要はありません。以下の例は、オプショナルの文字列と、暗黙的にアンラップされるオプショナルの文字列の間での、それらのラップされた値に明示的なStringとしてアクセスする場合での挙動の違いを示します:

  1. let possibleString: String? = "An optional string."
  2. let forcedString: String = possibleString! // requires an exclamation point(感嘆符が要求されます)
  3. let assumedString: String! = "An implicitly unwrapped optional string."
  4. let implicitString: String = assumedString // no need for an exclamation point(感嘆符の必要はありません)

You can think of an implicitly unwrapped optional as giving permission for the optional to be force-unwrapped if needed. When you use an implicitly unwrapped optional value, Swift first tries to use it as an ordinary optional value; if it can’t be used as an optional, Swift force-unwraps the value. In the code above, the optional value assumedString is force-unwrapped before assigning its value to implicitString because implicitString has an explicit, non-optional type of String. In code below, optionalString doesn’t have an explicit type so it’s an ordinary optional. あなたは暗黙的にアンラップされるオプショナルを、必要に応じて強制アンラップされる許可をそのオプショナルに与えていると考えることができます。あなたがある暗黙的にアンラップされるオプショナル値を使う場合、Swiftはまずそれを普通のオプショナル値として使おうと試みます;それがオプショナルとして使用できないならば、Swiftは値を強制アンラップします。上のコードにおいて、オプショナル値assumedStringは強制アンラップされます、それの値をimplicitStringに割り当てる前にです、なぜならimplicitStringはある明示的な、非オプショナル型のStringを持つからです。下のコードにおいて、optionalStringは明示的な型を持ちません、それでそれは普通のオプショナルです。

  1. let optionalString = assumedString
  2. // The type of optionalString is "String?" and assumedString isn't force-unwrapped.(optionalString の型は "String?" です、そして assumedString は強制アンラップされません。)

If an implicitly unwrapped optional is nil and you try to access its wrapped value, you’ll trigger a runtime error. The result is exactly the same as if you place an exclamation point after a normal optional that doesn’t contain a value. 暗黙的にアンラップされるオプショナルがnilであり、あなたがそれのラップされた値にアクセスしようとするならば、あなたは実行時エラーを引き起こします。その結果は、あなたが値を含まない通常のオプショナルの後に感嘆符を置いた場合と正確に同じものです。

You can check whether an implicitly unwrapped optional is nil the same way you check a normal optional: あなたは、暗黙的にアンラップされるオプショナルがnilであるかどうかを確認することが、あなたが通常のオプショナルを調べるのと同じ方法で可能です。

  1. if assumedString != nil {
  2. print(assumedString!)
  3. }
  4. // Prints "An implicitly unwrapped optional string."(「暗黙的にアンラップされるオプショナルの文字列。」を出力します)

You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement: あなたは、また、暗黙的にアンラップされるオプショナルをオプショナル束縛とともに使うことができます、1つの文でその値を確認してアンラップするためには:

  1. if let definiteString = assumedString {
  2. print(definiteString)
  3. }
  4. // Prints "An implicitly unwrapped optional string."(「暗黙的にアンラップされるオプショナルの文字列。」を出力します)

Note 注意

Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable. ある変数がその後のある時点でnilになる可能性がある時には、暗黙的にアンラップされるオプショナルを使用しないでください。あなたがある変数の生涯のある時期にnil値について確認する必要があるならば、必ず普通のオプショナル型を使ってください。

Error Handling エラーの処理

You use error handling to respond to error conditions your program may encounter during execution. あなたは、エラー処理を使ってあなたのプログラムが実行の間に遭遇するエラー状態に応答することができます。

In contrast to optionals, which can use the presence or absence of a value to communicate success or failure of a function, error handling allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program. オプショナルと対比して(それは値の有無を使って、ある関数の成否を伝えることができます)、エラー処理はあなたに根本的な失敗の原因を突き止めること、そして、必要ならば、そのエラーをあなたのプログラムの別の部分に伝えることを可能にします。

When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately. ある関数がエラー状態に遭遇するとき、それはあるエラーをスローします(投げます)。その関数の呼び出し側はそのときそのエラーをキャッチして(捕まえて)適切に応答することができます。

  1. func canThrowAnError() throws {
  2. // this function may or may not throw an error(この関数はエラーをスローするかもしれないししないかもしれない)
  3. }

A function indicates that it can throw an error by including the throws keyword in its declaration. When you call a function that can throw an error, you prepend the try keyword to the expression. ある関数は、それがエラーをスローできることをthrowsキーワードをそれの宣言に含めることによって示します。あなたがエラーをスローできる関数を呼ぶとき、あなたはtryキーワードをその式の前に追加します。

Swift automatically propagates errors out of their current scope until they’re handled by a catch clause. スウィフトは自動的に、エラーをそれの現在のスコープの外に、それがcatch節によって取り扱われるまで伝えます。

  1. do {
  2. try canThrowAnError()
  3. // no error was thrown(エラーはスローされなかった)
  4. } catch {
  5. // an error was thrown(エラーがスローされた)
  6. }

A do statement creates a new containing scope, which allows errors to be propagated to one or more catch clauses. do文はひとつの新しく取り囲んでいるスコープを作成します、それはエラーに1つ以上のcatch節に伝えられることを可能にします。

Here’s an example of how error handling can be used to respond to different error conditions: ここにどのようにエラー処理が異なるエラー状態に応答するために使われることができるかの例があります:

  1. func makeASandwich() throws {
  2. // ...
  3. }
  4. do {
  5. try makeASandwich()
  6. eatASandwich()
  7. } catch SandwichError.outOfCleanDishes {
  8. washDishes()
  9. } catch SandwichError.missingIngredients(let ingredients) {
  10. buyGroceries(ingredients)
  11. }

In this example, the makeASandwich() function will throw an error if no clean dishes are available or if any ingredients are missing. Because makeASandwich() can throw an error, the function call is wrapped in a try expression. By wrapping the function call in a do statement, any errors that are thrown will be propagated to the provided catch clauses. この例において、makeASandwich()関数は、綺麗な皿が利用可能でないならばまたは何の食材も見つからないならばエラーをスローします。makeASandwich()はエラーをスロー可能なので、この関数呼び出しはtry式で包まれます。その関数呼び出しをdo文の中に包み込むことによって、スローされるどんなエラーも添付のcatch節に伝えられるようになります。

If no error is thrown, the eatASandwich() function is called. If an error is thrown and it matches the SandwichError.outOfCleanDishes case, then the washDishes() function will be called. If an error is thrown and it matches the SandwichError.missingIngredients case, then the buyGroceries(_:) function is called with the associated [String] value captured by the catch pattern. エラーがスローされないならば、eatASandwich()関数が呼び出されます。エラーがスローされてそれがSandwichError.outOfCleanDishesケース節にマッチするならば、そのときwashDishes()関数が呼ばれます。エラーがスローされてそれがSandwichError.missingIngredientsケース節にマッチするならば、そのときbuyGroceries(_:)関数がそのcatchパターンによってキャプチャされた[String]関連値とともに呼ばれます。

Throwing, catching, and propagating errors is covered in greater detail in Error Handling. エラーのスロー、キャッチ、そして伝達は、詳細にエラー処理において扱われます。

Assertions and Preconditions 表明と前提条件

Assertions and preconditions are checks that happen at runtime. You use them to make sure an essential condition is satisfied before executing any further code. If the Boolean condition in the assertion or precondition evaluates to true, code execution continues as usual. If the condition evaluates to false, the current state of the program is invalid; code execution ends, and your app is terminated. 表明前提条件は、起こることを実行時で調べられます。あなたはそれらを使って、必要不可欠な条件が満たされるのを何らかのその先のコードが実行される前に確実なものにします。表明または前提条件におけるブール条件がtrueに評価されるならば、コードは普段通り続けて実行されます。条件がfalseに評価されるならば、プログラムの現在の状態は無効です;コード実行は止まり、そしてあなたのアプリは終了させられます。

You use assertions and preconditions to express the assumptions you make and the expectations you have while coding, so you can include them as part of your code. Assertions help you find mistakes and incorrect assumptions during development, and preconditions help you detect issues in production. あなたは表明と前提条件を使うことであなたのする想定とあなたが持つ期待をコーディングの間に表します、それであなたはそれらをあなたのコードの一部として含めることができます。表明は、あなたが失策や間違った想定を見つけるのを開発中に助けます、そして前提条件は、あなたが製品における問題点を見抜くのを助けます。

In addition to verifying your expectations at runtime, assertions and preconditions also become a useful form of documentation within the code. Unlike the error conditions discussed in Error Handling above, assertions and preconditions aren’t used for recoverable or expected errors. Because a failed assertion or precondition indicates an invalid program state, there’s no way to catch a failed assertion. あなたの期待を実行時で実証するのに加えて、表明と前提条件はまたコード内部での有用な文書化形式となります。上のエラー処理で議論されるエラー条件とは違い、表明と前提条件は回復できるまたは予想されたエラーに対して使われません。失敗した表明または前提条件は無効なプログラム状態を示すことから、失敗した表明を受け止めるための方法はありません。

Using assertions and preconditions isn’t a substitute for designing your code in such a way that invalid conditions are unlikely to arise. However, using them to enforce valid data and state causes your app to terminate more predictably if an invalid state occurs, and helps make the problem easier to debug. Stopping execution as soon as an invalid state is detected also helps limit the damage caused by that invalid state. 表明と前提条件を使用することは、無効な条件が思いもよらず起こるようなあなたのコードの設計に対する代役ではありません。しかしながら、それらを使って有効なデータと状態を遵守させることは、あなたのアプリに不正な状態が生じる場合により予測のつく結びとなるようにします、そして問題をより簡単にデバッグする助けとなります。無効な状態が検知されるやいなや実行を停止することはまた、その無効な状態によって起こされる被害を抑えます。

The difference between assertions and preconditions is in when they’re checked: Assertions are checked only in debug builds, but preconditions are checked in both debug and production builds. In production builds, the condition inside an assertion isn’t evaluated. This means you can use as many assertions as you want during your development process, without impacting performance in production. 表明と前提条件の間の違いは、それらが調べられる時にあります:表明はデバッグビルドにおいてのみ調べられます、しかし前提条件はデバッグおよび製品(プロダクション)ビルドの両方において調べられます。プロダクションビルドでは、表明内の条件は評価されません。これが意味するのは、あなたは多くの表明をあなたが望むだけあなたの開発過程の間に使用できる、製品での性能に影響を与えることなしに、ということです。

Debugging with Assertions 表明を使ってデバッグする

You write an assertion by calling the assert(_:_:file:line:) function from the Swift standard library. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false. For example: あなたは表明をassert(_:_:file:line:)関数をSwift標準ライブラリから呼び出すことによって記述します。あなたはこの関数に、trueまたはfalseに評価する式と条件の結果がfalseであるならば表示するメッセージを渡します。例えば:

  1. let age = -3
  2. assert(age >= 0, "A person's age can't be less than zero.")
  3. // This assertion fails because -3 isn't >= 0.(この表明は失敗する、なぜなら-3 は >= 0 ではないから。)

In this example, code execution continues if age >= 0 evaluates to true, that is, if the value of age is nonnegative. If the value of age is negative, as in the code above, then age >= 0 evaluates to false, and the assertion fails, terminating the application. この例において、コード実行はage >= 0trueに評価されるならば、すなわちageの値が負でないならば継続します。ageの値が負であるならば、上のコードでのように、そのときage >= 0falseに評価され、そして表明は失敗して、アプリケーションを終了します。

You can omit the assertion message—for example, when it would just repeat the condition as prose. あなたは表明メッセージを省略できます — 例えば、それが単に条件を単調に繰り返す場合。

  1. assert(age >= 0)

If the code already checks the condition, you use the assertionFailure(_:file:line:) function to indicate that an assertion has failed. For example: コードがすでに条件を調べるならば、あなたはassertionFailure(_:file:line:)関数を使って表明が失敗していることを示してください。例えば:

  1. if age > 10 {
  2. print("You can ride the roller-coaster or the ferris wheel.")
  3. } else if age >= 0 {
  4. print("You can ride the ferris wheel.")
  5. } else {
  6. assertionFailure("A person's age can't be less than zero.")
  7. }

Enforcing Preconditions 前提条件の遵守

Use a precondition whenever a condition has the potential to be false, but must definitely be true for your code to continue execution. For example, use a precondition to check that a subscript isn’t out of bounds, or to check that a function has been passed a valid value. ある条件が偽である可能性をもつ、しかしdefinitelyがあなたのコードの実行の継続のためにtrueでなければならない時はいつでも前提条件を使ってください。例えば、前提時要件を使って、ある添え字が範囲外でないことを調べてください、またはある関数が有効な値を渡されていることを確認してください。

You write a precondition by calling the precondition(_:_:file:line:) function. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false. For example: あなたは、前提条件をprecondition(_:_:file:line:)関数を呼び出すことによって記述します。あなたはこの関数に、trueまたはfalseに評価する式と条件の結果がfalseであるならば表示するメッセージを渡します。例えば:

  1. // In the implementation of a subscript...(ある添え字の実装において...)
  2. precondition(index > 0, "Index must be greater than zero.")

You can also call the preconditionFailure(_:file:line:) function to indicate that a failure has occurred—for example, if the default case of a switch was taken, but all valid input data should have been handled by one of the switch’s other cases. あなたはまた、preconditionFailure(_:file:line:)関数を呼び出して失敗がすでに起こっていることを示すことができます — 例えば、あるスイッチ文の省略時のケース節が取られた、しかし全ての有効な入力データがそのスイッチ文の他のケース節の1つによって取り扱われてしまっている場合。

Note 注意

If you compile in unchecked mode (-Ounchecked), preconditions aren’t checked. The compiler assumes that preconditions are always true, and it optimizes your code accordingly. However, the fatalError(_:file:line:) function always halts execution, regardless of optimization settings. あなたが未検査モード(-Ounchecked)でコンパイルするならば、前提条件は調べられません。コンパイラは、その前提条件が常にtrueであるとみなします、そしてそれはあなたのコードをそれを受けて最適化します。しかしながら、fatalError(_:file:line:)関数は常に実行を停止します、最適化設定に関係なく。

You can use the fatalError(_:file:line:) function during prototyping and early development to create stubs for functionality that hasn’t been implemented yet, by writing fatalError("Unimplemented") as the stub implementation. Because fatal errors are never optimized out, unlike assertions or preconditions, you can be sure that execution always halts if it encounters a stub implementation. あなたは、fatalError(_:file:line:)関数を試作段階および開発初期の間に使って、まだ実装されていない機能性に対してスタブ(代用品)を作成することが、fatalError("Unimplemented")をスタブ実装として記述することによって行えます。致命的なエラーは決して間違って最適化されません、表明や前提条件と違います、あなたは実行が常に停止することをそれがスタブ実装に遭遇する場合には確信できます。

A Swift Tour スウィフトツアー

Basic Operators 基本の演算子