Guides and Sample Code

Developer

The Swift Programming Language (Swift 4.1)

iBooks
On This Page

Types

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it’s defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values.
スウィフトには、2つの種類の型:名前付きの型と複合の型があります。名前付きの型は、それが定義される時に特定の名前を与えられることができる型です。名前付きの型は、クラス、構造体、列挙、そしてプロトコルを含みます。例えば、MyClassという名前をつけられるユーザー定義のクラスのインスタンスは、型MyClassを持ちます。ユーザー定義の名前付きの型に加えて、スウィフト標準ライブラリは、配列、辞書、そしてオプショナル値を表すものたちを含む、多くの一般に使われる名前付きの型を定義します。

Data types that are normally considered basic or primitive in other languages—such as types that represent numbers, characters, and strings—are actually named types, defined and implemented in the Swift standard library using structures. Because they’re named types, you can extend their behavior to suit the needs of your program, using an extension declaration, discussed in Extensions and Extension Declaration.
他の言語で通常は基本的またはプリミティブであるとみなされるデータ型 ― 例えば数、文字、そして文字列を表す型 ― これらは実際に名前付きの型で、構造体を使用してスウィフト標準ライブラリにおいて定義および実装されます。それらが名前付きの型であるので、あなたはそれらの挙動を、拡張および拡張宣言で議論される拡張宣言を使って、あなたのプログラムの必要に応じて拡張することができます。

A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types. A compound type may contain named types and other compound types. For instance, the tuple type (Int, (Int, Int)) contains two elements: The first is the named type Int, and the second is another compound type (Int, Int).
複合の型は名前のない型です、そしてスウィフト言語自身によって定義されます。2つの複合の型:関数型とタプル型があります。ひとつの複合の型は、名前付きの型や他の複合の型を含むかもしれません。たとえば、タプル型(Int, (Int, Int))は、2つの要素を含みます:第一は名前付きの型Intです、そして第二は別の複合の型(Int, Int)です。

You can put parentheses around a named type or a compound type. However, adding parentheses around a type doesn’t have any effect. For example, (Int) is equivalent to Int.
あなたは、名前付きの型や複合の型の周りに丸括弧を置くことができます。けれども、ある型の周りに丸括弧を加えることは全く影響はありません。例えば、(Int)Intに等しいです。

This chapter discusses the types defined in the Swift language itself and describes the type inference behavior of Swift.
この章は、スウィフト言語それ自身によって定義される型を議論して、スウィフトの型推論挙動を記載します。

Grammar of a type
型の文法

type array-type­

type dictionary-type­

type function-type­

type type-identifier­

type tuple-type­

type optional-type­

type implicitly-unwrapped-optional-type­

type protocol-composition-type­

type metatype-type­

type Any­

type Self­

type type­

Type Annotation
型注釈

A type annotation explicitly specifies the type of a variable or expression. Type annotations begin with a colon (:) and end with a type, as the following examples show:
ある型注釈は、明確に変数または式の型を指定します。型注釈は、以下の例が示すように、コロン(:)で始まりひとつの型で終わります:

  1. let someTuple: (Double, Double) = (3.14159, 2.71828)
  2. func someFunction(a: Int) { /* ... */ }

In the first example, the expression someTuple is specified to have the tuple type (Double, Double). In the second example, the parameter a to the function someFunction is specified to have the type Int.
最初の例で、式someTupleは、タプル型(Double, Double)を持つと指定されます。第二の例で関数someFunctionのためのパラメータaは、型Intを持つ指定されます。

Type annotations can contain an optional list of type attributes before the type.
型注釈は、型の前に任意の型属性のリストを含むことができます。

Grammar of a type annotation
型注釈の文法

type-annotation attributes­opt­inout­opt­type­

Type Identifier
型識別子

A type identifier refers to either a named type or a type alias of a named or compound type.
型識別子は、名前付きの型か、名前付きまたは複合の型の型エイリアスに言及します。

Most of the time, a type identifier directly refers to a named type with the same name as the identifier. For example, Int is a type identifier that directly refers to the named type Int, and the type identifier Dictionary<String, Int> directly refers to the named type Dictionary<String, Int>.
ほとんどの場合、型識別子は、名前付きの型に、その識別子と同じ名前で直接に言及します。例えば、Intは、直接に名前付きの型Intに言及する型識別子です、そして型識別子Dictionary<String, Int>は、直接に名前付きの型Dictionary<String, Int>に言及します。

There are two cases in which a type identifier doesn’t refer to a type with the same name. In the first case, a type identifier refers to a type alias of a named or compound type. For instance, in the example below, the use of Point in the type annotation refers to the tuple type (Int, Int).
ある型識別子がある型に同じ名前で言及しない2つの場合があります。第一の場合には、型識別子は、名前付きまたは複合の型の型エイリアスに言及します。たとえば、下記の例で、型注釈においてPointを使うことは、タプル型(Int, Int)に言及します。

  1. typealias Point = (Int, Int)
  2. let origin: Point = (0, 0)

In the second case, a type identifier uses dot (.) syntax to refer to named types declared in other modules or nested within other types. For example, the type identifier in the following code references the named type MyType that is declared in the ExampleModule module.
第二の場合には、型識別子は、他のモジュールで宣言される、または他の型の内部で入れ子にされる名前付きの型を参照するためにドット(.)構文を使用します。例えば、以下のコードの型識別子は、ExampleModuleモジュールで宣言される名前付きの型MyTypeを参照します。

  1. var someValue: ExampleModule.MyType

Grammar of a type identifier
型識別子の文法

type-identifier type-name­generic-argument-clause­opt­ type-name­generic-argument-clause­opt­type-identifier­

type-name identifier­

Tuple Type
タプル型

A tuple type is a comma-separated list of types, enclosed in parentheses.
タプル型は、丸括弧で囲まれた、コンマ区切りのいくらかの型のリストです。

You can use a tuple type as the return type of a function to enable the function to return a single tuple containing multiple values. You can also name the elements of a tuple type and use those names to refer to the values of the individual elements. An element name consists of an identifier followed immediately by a colon (:). For an example that demonstrates both of these features, see Functions with Multiple Return Values.
あなたは、関数の戻り型としてタプル型を使って、その関数に複数の値を含んでいる一つのタプルを返すのを可能にすることができます。あなたは、また、タプル型の要素に名をつけることができて、それらの名前を個々の要素の値に言及するために使用することができます。要素名は、識別子に直ちにコロン(:)が続くものから成ります。これらの特徴の両方を示す例のために、複数の戻り値をもつ関数を見てください。

When an element of a tuple type has a name, that name is part of the type.
あるタプル型の要素が名前を持つ場合、その名前は型の一部です。

  1. var someTuple = (top: 10, bottom: 12) // someTuple is of type (top: Int, bottom: Int) (someTupleは型 (top: Int, bottom: Int) です)
  2. someTuple = (top: 4, bottom: 42) // OK: names match (OK: 名前が一致)
  3. someTuple = (9, 99) // OK: names are inferred (OK: 名前は推論されます)
  4. someTuple = (left: 5, right: 5) // Error: names don't match (エラー: 名前が一致しない)

All tuple types contain two or more types, except for Void which is a type alias for the empty tuple type, ().
すべてのタプル型は2つまたはそれ以上の型を含みます、しかし空のタプル型、()に対する型エイリアスであるVoidを除きます。

Grammar of a tuple type
タプル型の文法

tuple-type tuple-type-element­tuple-type-element-list­

tuple-type-element-list tuple-type-element­ tuple-type-element­tuple-type-element-list­

tuple-type-element element-name­type-annotation­ type­

element-name identifier­

Function Type
関数型

A function type represents the type of a function, method, or closure and consists of a parameter and return type separated by an arrow (->):
関数型は、ある関数、メソッド、またはクロージャの型を表して、矢印(->)で区切られるパラメータと戻り型から成ります:

  • (parameter type) -> return type

The parameter type is comma-separated list of types. Because the return type can be a tuple type, function types support functions and methods that return multiple values.
parameter typeコンマ区切りの型のリストです。return typeはタプル型であることが可能なので、関数型は複数の値を返す関数およびメソッドをサポートします。

A parameter of the function type () -> T (where T is any type) can apply the autoclosure attribute to implicitly create a closure at its call sites. This provides a syntactically convenient way to defer the evaluation of an expression without needing to write an explicit closure when you call the function. For an example of an autoclosure function type parameter, see Autoclosures.
関数型() -> T(ここでTはどんな型でも)のあるパラメータは、autoclosure属性を適用することによって、あるクロージャを暗黙的にそれの呼び出し領域で作成することができます。これは、あなたがその関数を呼び出す時に明示的なクロージャを書く必要なしに、ある式の評価を延期する統語的に便利な方法を提供します。自動クロージャ関数型パラメータの例として、自動クロージャを見てください。

A function type can have a variadic parameter in its parameter type. Syntactically, a variadic parameter consists of a base type name followed immediately by three dots (...), as in Int.... A variadic parameter is treated as an array that contains elements of the base type name. For instance, the variadic parameter Int... is treated as [Int]. For an example that uses a variadic parameter, see Variadic Parameters.
関数型は、そのパラメータ型において可変長パラメータを持つことができます。統語的には、可変長パラメータは、Int...のように、基となる型名に直ちに3つの点(...)が続くものから成ります。可変長パラメータは、基本の型の名前の要素たちが入っている配列とみなされます。たとえば、可変長パラメータInt...[Int]とみなされます。可変長パラメータを使う例のために、可変長パラメータを見てください。

To specify an in-out parameter, prefix the parameter type with the inout keyword. You can’t mark a variadic parameter or a return type with the inout keyword. In-out parameters are discussed in In-Out Parameters.
in-outパラメータを指定するために、inoutキーワードをそのパラメータ型の前に置いてください。あなたは、可変長パラメータまたは戻り型にinoutキーワードで印をつけることができません。in-outパラメータは、in-outパラメータで議論されます。

If a function type has only one parameter and that parameter’s type is a tuple type, then the tuple type must be parenthesized when writing the function’s type. For example, ((Int, Int)) -> Void is the type of a function that takes a single parameter of the tuple type (Int, Int) and doesn’t return any value. In contrast, without parentheses, (Int, Int) -> Void is the type of a function that takes two Int parameters and doesn’t return any value. Likewise, because Void is a type alias for (), the function type (Void) -> Void is the same as (()) -> ()—a function that takes a single argument that is an empty tuple. These types are not the same as () -> ()—a function that takes no arguments.
ある関数型がただ1つだけのパラメータを持ちそしてそのパラメータの型がタプル型であるならば、その場合そのタプル型は関数の型を記述する時に丸括弧に入れられなければなりません。例えば、((Int, Int)) -> Voidは、タプル型(Int, Int)の単一のパラメータを取り、何ら値を返さない関数の型です対して、丸括弧なしで、(Int, Int) -> Voidは、2つのIntパラメータを取り、何ら値を返さない関数の型です。同様に、Void()に対する型エイリアスであることから、関数型(Void) -> Void(()) -> () — ただ1つの引数を取りそれが空のタプルである関数、と同じです。これらの型は、() -> () — 引数を取らない関数、と同じではありません。

Argument names in functions and methods are not part of the corresponding function type. For example:
関数やメソッドの引数名は、対応する関数型の一部ではありません。例えば:

  1. func someFunction(left: Int, right: Int) {}
  2. func anotherFunction(left: Int, right: Int) {}
  3. func functionWithDifferentLabels(top: Int, bottom: Int) {}
  4. var f = someFunction // The type of f is (Int, Int) -> Void, not (left: Int, right: Int) -> Void.
  5. f = anotherFunction // OK
  6. f = functionWithDifferentLabels // OK
  7. func functionWithDifferentArgumentTypes(left: Int, right: String) {}
  8. f = functionWithDifferentArgumentTypes // Error (エラー)
  9. func functionWithDifferentNumberOfArguments(left: Int, right: Int, top: Int) {}
  10. f = functionWithDifferentNumberOfArguments // Error (エラー)

Because argument labels are not part of a function’s type, you omit them when writing a function type.
引数ラベルは関数の型の一部ではないことから、あなたはそれらを関数型を書く時に省略します。

  1. var operation: (lhs: Int, rhs: Int) -> Int // Error
  2. var operation: (_ lhs: Int, _ rhs: Int) -> Int // OK
  3. var operation: (Int, Int) -> Int // OK

If a function type includes more than a single arrow (->), the function types are grouped from right to left. For example, the function type (Int) -> (Int) -> Int is understood as (Int) -> ((Int) -> Int)—that is, a function that takes an Int and returns another function that takes and returns an Int.
ある関数型がただ1つだけの矢印(->)ではなくもっと多く含むならば、その関数型は右から左にグループにされます。例えば、関数型(Int) -> (Int) -> Intは、(Int) -> ((Int) -> Int)として理解されます ― すなわち、ひとつのIntを取って、ひとつのIntを取りそして返す別の関数を返す関数。

Function types that can throw an error must be marked with the throws keyword, and function types that can rethrow an error must be marked with the rethrows keyword. The throws keyword is part of a function’s type, and nonthrowing functions are subtypes of throwing functions. As a result, you can use a nonthrowing function in the same places as a throwing one. Throwing and rethrowing functions are described in Throwing Functions and Methods and Rethrowing Functions and Methods.
エラーを投げ掛けること(スロー)ができる関数型は、throwsキーワードで印されなければなりません、そしてエラーを再度投げ掛けること(再スロー)ができる関数型は、rethrowsキーワードで印されなければなりません。throwsキーワードは関数の型の一部です、そしてスローを行わない関数はスロー関数の下位型です。結果として、あなたは非スロー関数をスロー関数と同じ場所で使うことができます。スローおよび再スロー関数は、スロー関数とメソッド再スロー関数とメソッドにおいて記述されます。

Restrictions for Nonescaping Closures
非脱出クロージャに対する規制

A parameter that’s a nonescaping function can’t be passed as an argument to another nonescaping function parameter. This restriction helps Swift perform more of its checks for conflicting access to memory at compile time instead of at runtime. For example:
非脱出関数であるパラメータは、別の非脱出関数パラメータに引数として渡されることはできません。この規制は、スウィフトが実行時ではなくコンパイル時にメモリへのアクセスの衝突についてより多くのそれの検査を実行する助けとなります。例えば:

  1. let external: (Any) -> Void = { _ in () }
  2. func takesTwoFunctions(first: (Any) -> Void, second: (Any) -> Void) {
  3. first(first) // Error (エラー)
  4. second(second) // Error (エラー)
  5. first(second) // Error (エラー)
  6. second(first) // Error (エラー)
  7. first(external) // OK
  8. external(first) // OK
  9. }

In the code above, both of the parameters to takesTwoFunctions(first:second:) are functions. Neither parameter is marked @escaping, so they’re both nonescaping as a result.
上のコードにおいて、takesTwoFunctions(first:second:)へのパラメータは両方とも関数です。どちらのものも@escapingと印されません、それでそれらは両方とも非脱出です。

The four function calls marked “Error” in the example above cause compiler errors. Because the first and second parameters are nonescaping functions, they can’t be passed as arguments to another nonescaping function parameter. In contrast, the two function calls marked “OK” don’t cause a compiler error. These function calls don’t violate the restriction because external isn’t one of the parameters of takesTwoFunctions(first:second:).
上の例において「Error」と記される4つの関数呼び出しは、コンパイラエラーを引き起こします。firstおよびsecondパラメータは非脱出関数であることから、それらは引数として別の非脱出関数パラメータとして渡されることができません。対照的に、「OK」と記される2つの関数呼び出しは、コンパイラエラーを引き起こしません。これらの関数呼び出しは制約に違反しません、なぜならexternaltakesTwoFunctions(first:second:)のパラメータの1つだからです。

If you need to avoid this restriction, mark one of the parameters as escaping, or temporarily convert one of the nonescaping function parameters to an escaping function by using the withoutActuallyEscaping(_:do:) function. For information about avoiding conflicting access to memory, see Memory Safety.
あなたがこの規制を回避する必要があるならば、パラメータの1つを脱出すると印してください、または一時的に非脱出関数パラメータの1つを脱出関数へとwithoutActuallyEscaping(_:do:)関数を使うことによって変換してください。メモリへのアクセスの衝突の回避についての情報として、メモリ安全を見てください。

Grammar of a function type
関数型の文法

function-type attributes­opt­function-type-argument-clause­throws­opt­->­type­

function-type attributes­opt­function-type-argument-clause­rethrows­->­type­

function-type-argument-clause

function-type-argument-clause function-type-argument-list­...­opt­

function-type-argument-list function-type-argument­ function-type-argument­function-type-argument-list­

function-type-argument attributes­opt­inout­opt­type­ argument-label­type-annotation­

argument-label identifier­

Array Type
配列型

The Swift language provides the following syntactic sugar for the Swift standard library Array<Element> type:
スウィフト言語は、スウィフト標準ライブラリのArray<Element>型のために以下の構文糖衣を提供します:

  • [type]

In other words, the following two declarations are equivalent:
言い換えると、以下の2つの宣言は、等しいです:

  1. let someArray: Array<String> = ["Alex", "Brian", "Dave"]
  2. let someArray: [String] = ["Alex", "Brian", "Dave"]

In both cases, the constant someArray is declared as an array of strings. The elements of an array can be accessed through subscripting by specifying a valid index value in square brackets: someArray[0] refers to the element at index 0, "Alex".
両方の場合で、定数のsomeArrayは、文字列の配列として宣言されます。配列の要素は、角括弧の中に有効なインデックス値を指定することによる添え字指定を通してアクセスされることができます:someArray[0]]は、インデックス0での要素、"Alex"に言及します。

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
あなたは、角括弧の対を入れにすることによって多次元配列をつくることができます、そこで要素の基本型の名前は最も内側の角括弧の対の中に含まれます。例えば、あなたは3つ固めた角括弧を使って整数の三次元配列をつくることができます:

  1. var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
多次元配列の要素にアクセスするとき、最も左の添え字インデックスは、最も外側の配列の中のそのインデックスでの要素に言及します。次の右の添え字インデックスは、1段階内側の入れ子にされた配列の中のそのインデックスでの要素に言及します。などなど。これは、上の例で、array3D[0][[1, 2], [3, 4]]に言及し、array3D[0][1][3, 4]に言及し、そしてarray3D[0][1][1]は値4に言及することを意味します。

For a detailed discussion of the Swift standard library Array type, see Arrays.
スウィフト標準ライブラリArray型の詳細な議論のために、配列を見てください。

Grammar of an array type
配列型の文法

array-type type­

Dictionary Type
辞書型

The Swift language provides the following syntactic sugar for the Swift standard library Dictionary<Key, Value> type:
スウィフト言語は、以下の構文糖衣をスウィフト標準ライブラリDictionary<Key, Value>型に提供します:

  • [key type: value type]

In other words, the following two declarations are equivalent:
言い換えると、以下の2つの宣言は、等しいです:

  1. let someDictionary: [String: Int] = ["Alex": 31, "Paul": 39]
  2. let someDictionary: Dictionary<String, Int> = ["Alex": 31, "Paul": 39]

In both cases, the constant someDictionary is declared as a dictionary with strings as keys and integers as values.
両方の場合で、定数someDictionaryは、キーとして文字列そして値として整数を持つ辞書として宣言されます。

The values of a dictionary can be accessed through subscripting by specifying the corresponding key in square brackets: someDictionary["Alex"] refers to the value associated with the key "Alex". The subscript returns an optional value of the dictionary’s value type. If the specified key isn’t contained in the dictionary, the subscript returns nil.
辞書の値は、角括弧の中に対応するキーを指定することによる添え字指定を通してアクセスされることができます:someDictionary["Alex"]はキー"Alex"と結び付けられた値に言及します。添え字は辞書のもつ値型のオプショナルの値を返します。指定されたキーがその辞書に含まれないならば、添え字はnilを返します。

The key type of a dictionary must conform to the Swift standard library Hashable protocol.
ある辞書のキーの型は、スウィフト標準ライブラリHashableプロトコルに準拠しなければなりません。

For a detailed discussion of the Swift standard library Dictionary type, see Dictionaries.
スウィフト標準ライブラリDictionary型の詳細な議論として、辞書を見てください。

Grammar of a dictionary type
辞書型の文法

dictionary-type type­type­

Optional Type
オプショナル型

The Swift language defines the postfix ? as syntactic sugar for the named type Optional<Wrapped>, which is defined in the Swift standard library. In other words, the following two declarations are equivalent:
スウィフト言語は、接尾辞?を構文糖衣として名前付きの型Optional<Wrapped>に対して定義します、それは、スウィフト標準ライブラリで定義されます。言い換えると、以下の2つの宣言は、等しいです:

  1. var optionalInteger: Int?
  2. var optionalInteger: Optional<Int>

In both cases, the variable optionalInteger is declared to have the type of an optional integer. Note that no whitespace may appear between the type and the ?.
両方の場合には、変数optionalIntegerは、オプショナル整数の型を持つと宣言されます。空白が型と?の間に現れないことに注意してください。

The type Optional<Wrapped> is an enumeration with two cases, none and some(Wrapped), which are used to represent values that may or may not be present. Any type can be explicitly declared to be (or implicitly converted to) an optional type. If you don’t provide an initial value when you declare an optional variable or property, its value automatically defaults to nil.
Optional<Wrapped>は、nonesome(Wrapped)、2つのケース節をもつ列挙です、それは、存在しているかもしれないししていないかもしれない値を表わすために使われます。あらゆる型は、オプショナル型であるとして明示的に宣言される(または暗黙的に変換される)ことができます。オプショナルの変数またはプロパティを宣言する時にあなたが最初の値を提供しないならば、その値は自動的に省略時のnilになります。

If an instance of an optional type contains a value, you can access that value using the postfix operator !, as shown below:
オプショナル型のインスタンスが値を含むならば、あなたが接尾辞演算子!を使用してその値にアクセスすることができます、以下に示すように:

  1. optionalInteger = 42
  2. optionalInteger! // 42

Using the ! operator to unwrap an optional that has a value of nil results in a runtime error.
!演算子を使ってnilの値を持つあるオプショナルをアンラップすることは、実行時エラーの結果になります。

You can also use optional chaining and optional binding to conditionally perform an operation on an optional expression. If the value is nil, no operation is performed and therefore no runtime error is produced.
あなたはまたオプショナル連鎖とオプショナル束縛を使って、あるオプショナルの式に関して演算を条件付きで実行することができます。その値がnilならば、演算は実行されません、したがって、実行時エラーは生じません。

For more information and to see examples that show how to use optional types, see Optionals.
より多くの情報のために、そしてオプショナル型を使う方法を示す例を見るために、オプショナルを見てください。

Grammar of an optional type
オプショナル型の文法

optional-type type­

Implicitly Unwrapped Optional Type
暗黙的にアンラップされるオプショナルの型

The Swift language defines the postfix ! as syntactic sugar for the named type Optional<Wrapped>, which is defined in the Swift standard library, with the additional behavior that it’s automatically unwrapped when it’s accessed. If you try to use an implicitly unwrapped optional that has a value of nil, you’ll get a runtime error. With the exception of the implicit unwrapping behavior, the following two declarations are equivalent:
スウィフト言語は、接尾辞!を構文糖衣としてスウィフト標準ライブラリで定義される名前付きの型Optional<Wrapped>に対して定義します、それはそれがアクセスされるとき自動的にアンラップされるという追加の挙動を含みます。あなたがnilの値を持つ暗黙的にアンラップされるオプショナルを使うことを試みるならば、あなたは実行時エラーを得るでしょう。暗黙的にアンラップされる挙動を除けば、以下の2つの宣言は等しいです:

  1. var implicitlyUnwrappedString: String!
  2. var explicitlyUnwrappedString: Optional<String>

Note that no whitespace may appear between the type and the !.
空白が型と!の間に現れないことに注意してください。

Because implicit unwrapping changes the meaning of the declaration that contains that type, optional types that are nested inside a tuple type or a generic type—such as the element types of a dictionary or array—can’t be marked as implicitly unwrapped. For example:
暗黙的にアンラップされることがその型を含む宣言の意味することを変えることから、タプル型や総称体型の内部に入れ子にされたオプショナル型—例えば辞書や配列に属する要素型など—は、暗黙的にアンラップされるように印されることはできません。例えば:

  1. let tupleOfImplicitlyUnwrappedElements: (Int!, Int!) // Error
  2. let implicitlyUnwrappedTuple: (Int, Int)! // OK
  3. let arrayOfImplicitlyUnwrappedElements: [Int!] // Error
  4. let implicitlyUnwrappedArray: [Int]! // OK

Because implicitly unwrapped optionals have the same Optional<Wrapped> type as optional values, you can use implicitly unwrapped optionals in all the same places in your code that you can use optionals. For instance, you can assign values of implicitly unwrapped optionals to variables, constants, and properties of optionals, and vice versa.
暗黙的にアンラップされるオプショナルがオプショナル値と同じOptional<Wrapped>型を持つことから、あなたは、あなたのコードにおいてあなたがオプショナルを使うことができるのと同じ場所すべてで暗黙的にアンラップされるオプショナルを使うことができます。たとえば、あなたは暗黙的にアンラップされるオプショナルの値を、オプショナルの変数、定数、そしてプロパティに代入することができます、その逆もまたできます。

As with optionals, if you don’t provide an initial value when you declare an implicitly unwrapped optional variable or property, its value automatically defaults to nil.
オプショナルと同様に、あなたが暗黙的にアンラップされるオプショナルの変数やプロパティに初期値を提供しないならば、その値は自動的に省略時のnilになります。

Use optional chaining to conditionally perform an operation on an implicitly unwrapped optional expression. If the value is nil, no operation is performed and therefore no runtime error is produced.
ある暗黙的にアンラップされるオプショナルの式に関して演算を条件付きで実行するために、オプショナル連鎖を使ってください。その値がnilならば、演算は実行されません、したがって、実行時エラーは生じません。

For more information about implicitly unwrapped optional types, see Implicitly Unwrapped Optionals.
暗黙的にアンラップされるオプショナル型の詳細については、暗黙的にアンラップされるオプショナルを見てください。

Grammar of an implicitly unwrapped optional type
暗黙的にアンラップされるオプショナル型の文法

implicitly-unwrapped-optional-type type­

Protocol Composition Type
プロトコル合成型

A protocol composition type defines a type that conforms to each protocol in a list of specified protocols, or a type that is a subclass of a given class and conforms to each protocol in a list of specified protocols. Protocol composition types may be used only when specifying a type in type annotations, in generic parameter clauses, and in generic where clauses.
プロトコル合成型が定義するのは、指定されたプロトコルのリストの各プロトコルに準拠する型、または指定されたクラスのサブクラスでそして指定されたプロトコルのリストの各プロトコルに準拠する型です。プロトコル合成型は、型注釈において、総称体パラメータ節において、そして総称体where節において型を指定する場合にのみ使われるでしょう。

Protocol composition types have the following form:
プロトコル合成型は、以下の形式を持ちます:

  • Protocol 1 & Protocol 2

A protocol composition type allows you to specify a value whose type conforms to the requirements of multiple protocols without explicitly defining a new, named protocol that inherits from each protocol you want the type to conform to. For example, you can use the protocol composition type ProtocolA & ProtocolB & ProtocolC instead of declaring a new protocol that inherits from ProtocolA, ProtocolB, and ProtocolC. Likewise, you can use SuperClass & ProtocolA instead of declaring a new protocol that is a subclass of SuperClass and conforms to ProtocolA.
プロトコル合成型は、あなたにそれの型が複数のプロトコルに属する要件に準拠するある値を、あなたがその型に準拠して欲しいプロトコル各々から継承する名前をつけられたある新しいプロトコルを明示的に定義する必要なしに指定させます。例えば、プロトコル合成型ProtocolA & ProtocolB & ProtocolCを使うことが、ProtocolAProtocolB、そしてProtocolCから継承する新しいプロトコルを宣言する代わりに行えます。同様に、あなたはSuperClass & ProtocolAを使うことが、SuperClassのサブクラスでProtocolAに準拠する新しいプロトコルを宣言する代わりに行えます。

Each item in a protocol composition list is one of the following; the list can contain at most one class:
プロトコル合成リストの各項目は以下のうちの1つです;リストは最大1つのクラスを含むことができます:

  • The name of a class
    あるクラスの名前

  • The name of a protocol
    あるプロトコルの名前

  • A type alias whose underlying type is a protocol composition type, a protocol, or a class.
    それの基礎をなす型がプロトコル合成型、プロトコル、またはクラスである型エイリアス。

When a protocol composition type contains type aliases, it’s possible for the same protocol to appear more than once in the definitions—duplicates are ignored. For example, the definition of PQR in the code below is equivalent to P & Q & R.
あるプロトコル合成型が型エイリアスを含む場合、同じプロトコルが1度以上多く定義の中に現れることが可能です — 重複は無視されます。例えば、以下のコードでのPQRの定義は、P & Q & Rと同等です。

  1. typealias PQ = P & Q
  2. typealias PQR = PQ & Q & R

Grammar of a protocol composition type
プロトコル構成型の文法

protocol-composition-type type-identifier­protocol-composition-continuation­

protocol-composition-continuation type-identifier­ protocol-composition-type­

Metatype Type
メタタイプ型

A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.
あるメタタイプ型は、いろいろなクラス型、構造体型、列挙型、そしていろいろなプロトコル型の内で、ある何らかの型のその型に言及します。

The metatype of a class, structure, or enumeration type is the name of that type followed by .Type. The metatype of a protocol type—not the concrete type that conforms to the protocol at runtime—is the name of that protocol followed by .Protocol. For example, the metatype of the class type SomeClass is SomeClass.Type and the metatype of the protocol SomeProtocol is SomeProtocol.Protocol.
あるクラス、構造体、または列挙型のメタタイプは、その型の名前に.Typeが続くものです。あるプロトコル型 ― 実行時にそのプロトコルに準拠する具象型ではない ― のメタタイプは、そのプロトコルの名前に.Protocolが続くものです。例えば、クラス型SomeClassのメタタイプはSomeClass.Typeです、そして、プロトコルSomeProtocolのメタタイプはSomeProtocol.Protocolです。

You can use the postfix self expression to access a type as a value. For example, SomeClass.self returns SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. You can call the type(of:) function with an instance of a type to access that instance’s dynamic, runtime type as a value, as the following example shows:
あなたは、接尾辞self式を使って、ある型に値としてアクセスすることができます。例えば、SomeClass.selfは、SomeClass自身を返します、SomeClassのインスタンスではなく。そして、SomeProtocol.selfは、SomeProtocol自身を返します、実行時にSomeProtocolに準拠するある型のインスタンスではなく。あなたは、ある型のインスタンスを使ってtype(of:)関数を呼び出して、そのインスタンスの持つ動的な、実行時の型にひとつの値としてアクセスできます、以下の例で示すように:

  1. class SomeBaseClass {
  2. class func printClassName() {
  3. print("SomeBaseClass")
  4. }
  5. }
  6. class SomeSubClass: SomeBaseClass {
  7. override class func printClassName() {
  8. print("SomeSubClass")
  9. }
  10. }
  11. let someInstance: SomeBaseClass = SomeSubClass()
  12. // The compile-time type of someInstance is SomeBaseClass, (someInstanceのコンパイル時での型は、SomeBaseClassです、)
  13. // and the runtime type of someInstance is SomeSubClass (そしてsomeInstanceの実行時での型は、SomeSubClassです)
  14. type(of: someInstance).printClassName()
  15. // Prints "SomeSubClass" (「 SomeSubClass 」を出力します)

For more information, see type(of:) in the Swift standard library.
詳細は、type(of:)をスウィフト標準ライブラリで見てください。

Use an initializer expression to construct an instance of a type from that type’s metatype value. For class instances, the initializer that’s called must be marked with the required keyword or the entire class marked with the final keyword.
イニシャライザ式を使って、ある型のインスタンスをその型のメタタイプ値から組み立ててください。クラスインスタンスに対しては、呼び出されるイニシャライザがrequiredキーワードで印されるか、クラス全体がfinalキーワードで印されなければなりません。

  1. class AnotherSubClass: SomeBaseClass {
  2. let string: String
  3. required init(string: String) {
  4. self.string = string
  5. }
  6. override class func printClassName() {
  7. print("AnotherSubClass")
  8. }
  9. }
  10. let metatype: AnotherSubClass.Type = AnotherSubClass.self
  11. let anotherInstance = metatype.init(string: "some string")

Grammar of a metatype type
メタタイプ型の文法

metatype-type type­Type­ type­Protocol­

Type Inheritance Clause
型継承節

A type inheritance clause is used to specify which class a named type inherits from and which protocols a named type conforms to. A type inheritance clause begins with a colon (:), followed by a list of type identifiers.
ある型継承節は、ある名前付きの型が継承するのはどのクラスからか、およびある名前付きの型が準拠するのはどのプロトコルに対してかを指定するために使われます。型継承節はコロン(:)で始まり、型識別子のリストが続きます。

Class types can inherit from a single superclass and conform to any number of protocols. When defining a class, the name of the superclass must appear first in the list of type identifiers, followed by any number of protocols the class must conform to. If the class doesn’t inherit from another class, the list can begin with a protocol instead. For an extended discussion and several examples of class inheritance, see Inheritance.
クラス型は、1つのスーパークラスから継承することができ、任意の数のプロトコルに準拠することができます。クラスを定義するとき、スーパークラスの名前は型識別子のリストにおいて最初に現れなければなりません、そしてそのクラスが準拠しなければならないいくらかのプロトコルが続きます。クラスが別のクラスから継承しないならば、このリストは代わりにプロトコルで始まることが出来ます。クラス継承の広範囲にわたる議論といくつかの例のために、継承を見てください。

Other named types can only inherit from or conform to a list of protocols. Protocol types can inherit from any number of other protocols. When a protocol type inherits from other protocols, the set of requirements from those other protocols are aggregated together, and any type that inherits from the current protocol must conform to all of those requirements.
他の名前付きの型は、プロトコルのリストから継承し準拠することだけができます。プロトコル型は、いくらかの他のプロトコルから継承することができます。プロトコル型が他のプロトコルから継承するとき、それらの他のプロトコルからの要件ひとそろいは一緒にまとめられます、そして、現在のプロトコルから継承するどんな型でもそれらの要件の全てに準拠しなければなりません。

A type inheritance clause in an enumeration definition can be either a list of protocols, or in the case of an enumeration that assigns raw values to its cases, a single, named type that specifies the type of those raw values. For an example of an enumeration definition that uses a type inheritance clause to specify the type of its raw values, see Raw Values.
列挙定義における型継承節は、プロトコルのリスト、または生の値をそれのケース節に割り当てる列挙のケース節においては、それらの生の値を指定する単一の名前付き型、このどちらかであることができます。その生の値の型を指定するために型継承節を使う列挙定義の例のために、生の値を見てください。

Grammar of a type inheritance clause
型継承節の文法

type-inheritance-clause type-inheritance-list­

type-inheritance-list type-identifier­ type-identifier­type-inheritance-list­

Type Inference
型推論

Swift uses type inference extensively, allowing you to omit the type or part of the type of many variables and expressions in your code. For example, instead of writing var x: Int = 0, you can write var x = 0, omitting the type completely—the compiler correctly infers that x names a value of type Int. Similarly, you can omit part of a type when the full type can be inferred from context. For instance, if you write let dict: Dictionary = ["A": 1], the compiler infers that dict has the type Dictionary<String, Int>.
スウィフトは広く型推論を使います、そして、あなたのコードにおいて型、または多くの変数および式の型の一部を省略できるようにします。例えば、var x: Int = 0を書く代わりに、あなたは型を完全に省略してvar x = 0と書くことができます ― コンパイラは、xが型Intの値に名をつけると正しく推測します。同じように、前後関係から完全に型が推論されることができるとき、あなたはある型の一部を省略することができます。たとえば、あなたがlet dict: Dictionary = ["A": 1]を書くならば、コンパイラはdictが型Dictionary<String, Int>を持つと推測します。

In both of the examples above, the type information is passed up from the leaves of the expression tree to its root. That is, the type of x in var x: Int = 0 is inferred by first checking the type of 0 and then passing this type information up to the root (the variable x).
上の例の両方とも、型情報は、式ツリーの葉っぱから、その根までさかのぼって渡されます。すなわち、var x: Int = 0の中のxの型は、最初に0の型を調べて、それからこの型情報を根(変数x)までさかのぼって渡すことによって推論されます。

In Swift, type information can also flow in the opposite direction—from the root down to the leaves. In the following example, for instance, the explicit type annotation (: Float) on the constant eFloat causes the numeric literal 2.71828 to have an inferred type of Float instead of Double.
スウィフトでは、型情報は逆方向にも流れます ― 根から下って葉っぱまで。例えば、以下の例において、定数eFloatでの明示的な型注釈(: Float)は、数値リテラル2.71828Floatの推論される型を持つようにします、Doubleではなく。

  1. let e = 2.71828 // The type of e is inferred to be Double. (eの型は、Doubleであると推測されます。
  2. let eFloat: Float = 2.71828 // The type of eFloat is Float.

Type inference in Swift operates at the level of a single expression or statement. This means that all of the information needed to infer an omitted type or part of a type in an expression must be accessible from type-checking the expression or one of its subexpressions.
スウィフトの型推論は、単一の式や文の水準で働きます。これは、ある式における省略される型や型の一部分を推論するために必要とされる情報のすべては、型を調べているその式またはそれの下位式の1つからアクセス可能でなければならないことを意味します。