属性
日本語を消す 英語を消す下記URLから引用し、日本語訳をつけてみました
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes
Add information to declarations and types.
宣言と型に情報を追加します。
There are two kinds of attributes in Swift — those that apply to declarations and those that apply to types. An attribute provides additional information about the declaration or type. For example, the discardableResult attribute on a function declaration indicates that, although the function returns a value, the compiler shouldn’t generate a warning if the return value is unused.
Swift には、宣言に適用される属性と型に適用される属性の 2 種類の属性があります。 属性は、宣言または型に関する追加情報を提供します。 たとえば、関数宣言の discardableResult 属性は、関数が値を返しても、戻り値が未使用の場合にコンパイラが警告を生成すべきではないことを示します。
You specify an attribute by writing the @ symbol followed by the attribute’s name and any arguments that the attribute accepts:
属性を指定するには、@ 記号の後に属性の名前と属性が受け入れる引数を記述します。
@<#attribute name#>
@<#attribute name#>(<#attribute arguments#>)
Some declaration attributes accept arguments that specify more information about the attribute and how it applies to a particular declaration. These attribute arguments are enclosed in parentheses, and their format is defined by the attribute they belong to.
一部の宣言属性は、属性に関する詳細情報とそれが特定の宣言にどのように適用されるかを指定する引数を受け取ります。 これらの属性引数はかっこで囲まれており、その形式は、それらが属する属性によって定義されます。
Attached macros and property wrappers also use attribute syntax. For information about how macros expand, see Macro-Expansion Expression. For information about property wrappers, see propertyWrapper.
添付されたマクロとプロパティ ラッパーも属性構文を使用します。 マクロがどのように展開されるかについては、「マクロ展開式」を参照してください。 プロパティ ラッパーについては、「propertyWrapper」をご覧ください。
Declaration Attributes
宣言の属性
You can apply a declaration attribute to declarations only.
宣言属性は宣言にのみ適用できます。
attached
添付
Apply the attached attribute to a macro declaration. The arguments to this attribute indicate the macro’s role. For a macro that has multiple roles, apply the attached macro multiple times, once for each role.
attached属性をマクロ宣言に適用します。 この属性の引数はマクロの役割を示します。 複数の役割を持つマクロの場合は、attachedマクロを役割ごとに 1 回ずつ複数回適用します。
The first argument to this attribute indicates the macros role:
この属性の最初の引数は、マクロの役割を示します。
Peer macros
Write peer as the first argument to this attribute. The type that implements the macro conforms to the PeerMacro protocol. These macros produce new declarations in the same scope as the declaration that the macro is attached to. For example, applying a peer macro to a method of a structure can define additional methods and properties on that structure.
この属性の最初の引数としてpeerを記載します。 マクロを実装するタイプは、PeerMacro プロトコルに準拠します。 これらのマクロは、マクロがアタッチされている宣言と同じスコープ内に新しい宣言を生成します。 たとえば、ピア マクロを構造体のメソッドに適用すると、その構造体に追加のメソッドとプロパティを定義できます。
Member macros
Write member as the first argument to this attribute. The type that implements the macro conforms to the MemberMacro protocol. These macros produce new declarations that are members of the type or extension that the macro is attached to. For example, applying a member macro to a structure declaration can define additional methods and properties on that structure.
この属性の最初の引数として member を記載します。 マクロを実装するタイプは、MemberMacro プロトコルに準拠します。 これらのマクロは、マクロが関連付けられている型または拡張子のメンバーである新しい宣言を生成します。 たとえば、メンバー マクロを構造体宣言に適用すると、その構造体に追加のメソッドとプロパティを定義できます。
Member attribute
Write memberAttribute as the first argument to this attribute. The type that implements the macro conforms to the MemberAttributeMacro protocol. These macros add attributes to members of the type or extension that the macro is attached to.
この属性の最初の引数として memberAttribute を記載します。 マクロを実装するタイプは、MemberAttributeMacro プロトコルに準拠します。 これらのマクロは、マクロが関連付けられている型または拡張子のメンバーに属性を追加します。
Accessor macros
Write accessor as the first argument to this attribute. The type that implements the macro conforms to the AccessorMacro protocol. These macros add accessors to the stored property they’re attached to, turning it into a computed property.
この属性の最初の引数としてaccessorを記載します。 マクロを実装するタイプは、AccessorMacro プロトコルに準拠します。 これらのマクロは、アクセサーがアタッチされている保存プロパティにアクセサーを追加し、それを計算プロパティに変換します。
Extension macros
Write extension as the first argument to this attribute. The type that implements the macro conforms to the ExtensionMacro protocol. These macros can add protocol conformance, a where clause, and new declarations that are members of the type the macro is attached to. If the macro adds protocol conformances, include the conformances: argument and specify those protocols. The conformance list contains protocol names, type aliases that refer to conformance list items, or protocol compositions of conformance list items. An extension macro on a nested type expands to an extension at the top level of that file. You can’t write an extension macro on an extension, a type alias, or a type that’s nested inside a function, or use an extension macro to add an extension that has a peer macro.
この属性の最初の引数としてextensionを記載します。 マクロを実装するタイプは、ExtensionMacro プロトコルに準拠します。 これらのマクロは、プロトコル準拠、where 句、およびマクロが接続されている型のメンバーである新しい宣言を追加できます。 マクロがプロトコル準拠を追加する場合は、conformance: 引数を含めて、それらのプロトコルを指定します。 適合リストには、プロトコル名、適合リスト項目を参照するタイプ エイリアス、または適合リスト項目のプロトコル構成が含まれます。 ネストされた型の拡張子マクロは、そのファイルの最上位レベルの拡張子に展開されます。 拡張機能、型エイリアス、または関数内にネストされた型に拡張マクロを記述したり、拡張マクロを使用してピア マクロを持つ拡張機能を追加したりすることはできません。
The peer, member, and accessor macro roles require a names: argument, listing the names of the symbols that the macro generates. The extension macro role also requires a names: argument if the macro adds declarations inside the extension. When a macro declaration includes the names: argument, the macro implementation must generate only symbol with names that match that list. That said, a macro need not generate a symbol for every listed name. The value for that argument is a list of one or more of the following:
ピア、メンバー、アクセサーのマクロの役割には、マクロが生成するシンボルの名前をリストする names: 引数が必要です。 マクロが拡張機能内に宣言を追加する場合、拡張機能マクロの役割には names: 引数も必要です。 マクロ宣言に names: 引数が含まれる場合、マクロ実装はそのリストに一致する名前を持つシンボルのみを生成する必要があります。 とはいえ、マクロはリストされたすべての名前に対してシンボルを生成する必要はありません。 その引数の値は、次の 1 つ以上のリストです。
named(<#name#>)where name is that fixed symbol name, for a name that’s known in advance.named(<#name#>)ここで、name は、事前にわかっている名前の固定シンボル名です。overloadedfor a name that’s the same as an existing symbol.overloaded既存のシンボルと同じ名前へ。prefixed(<#prefix#>)where prefix is prepended to the symbol name, for a name that starts with a fixed string.prefixed(<#prefix#>)固定文字列で始まる名前の場合、prefix がシンボル名の前に追加されます。suffixed(<#suffix#>where suffix is appended to the symbol name, for a name that ends with a fixed string.suffixed(<#suffix#>ここで suffix は、固定文字列で終わる名前の場合、シンボル名に追加されます。arbitraryfor a name that can’t be determined until macro expansion.arbitraryマクロ展開するまで決定できない名前へ。
As a special case, you can write prefixed($) for a macro that behaves similar to a property wrapper.
特殊なケースとして、プロパティ ラッパーと同様に動作するマクロにprefixed($)を付けることができます。
available
利用可能
Apply this attribute to indicate a declaration’s life cycle relative to certain Swift language versions or certain platforms and operating system versions.
この属性を適用して、特定の Swift 言語バージョンまたは特定のプラットフォームとオペレーティング システムのバージョンに関連した宣言のライフ サイクルを示します。
The available attribute always appears with a list of two or more comma-separated attribute arguments. These arguments begin with one of the following platform or language names:
available 属性は常に、2 つ以上のカンマ区切りの属性引数のリストとともに表示されます。 これらの引数は、次のプラットフォーム名または言語名のいずれかで始まります。
iOS iOSApplication Extension macOS macOSApplication Extension macCatalyst macCatalyst Application Extension watchOS watchOSApplication Extension tvOS tvOSApplication Extension visionOS visionOSApplicationExtensionswift
You can also use an asterisk (*) to indicate the availability of the declaration on all of the platform names listed above. An available attribute that specifies availability using a Swift version number can’t use the asterisk.
アスタリスク (*) を使用して、上記のすべてのプラットフォーム名で宣言が利用可能であることを示すこともできます。 Swift バージョン番号を使用して可用性を指定する available 属性では、アスタリスクを使用できません。
The remaining arguments can appear in any order and specify additional information about the declaration’s life cycle, including important milestones.
残りの引数は任意の順序で指定でき、重要なマイルストーンなど、宣言のライフサイクルに関する追加情報を指定できます。
- The
unavailableargument indicates that the declaration isn’t available on the specified platform. This argument can’t be used when specifying Swift version availability. unavailable引数は、指定されたプラットフォームで宣言が利用できないことを示します。 この引数は、Swift バージョンの可用性を指定する場合には使用できません。- The
introducedargument indicates the first version of the specified platform or language in which the declaration was introduced. It has the following form:introduced: <#version number#>The version number consists of one to three positive integers, separated by periods. introduced引数は、宣言が導入された指定されたプラットフォームまたは言語の最初のバージョンを示します。 これは次の形式になりintroduced: <#versionnumber#>バージョン番号は、ピリオドで区切られた 1 ~ 3 つの正の整数で構成されます。- The
deprecatedargument indicates the first version of the specified platform or language in which the declaration was deprecated. It has the following form:deprecated: <#version number#>The optional version number consists of one to three positive integers, separated by periods. Omitting the version number indicates that the declaration is currently deprecated, without giving any information about when the deprecation occurred. If you omit the version number, omit the colon (:) as well. deprecated引数は、宣言が非推奨になった、指定されたプラットフォームまたは言語の最初のバージョンを示します。 次の形式になりdeprecated: <#version number#>オプションのバージョン番号は、ピリオドで区切られた 1 ~ 3 つの正の整数で構成されます。 バージョン番号を省略すると、宣言が現在非推奨であることを示し、非推奨がいつ発生したかについての情報は提供されません。 バージョン番号を省略する場合は、コロン(:)も省略してください。- The
obsoletedargument indicates the first version of the specified platform or language in which the declaration was obsoleted. When a declaration is obsoleted, it’s removed from the specified platform or language and can no longer be used. It has the following form:obsoleted: <#version number#>The version number consists of one to three positive integers, separated by periods. obsoleted引数は、宣言が廃止された、指定されたプラットフォームまたは言語の最初のバージョンを示します。 宣言が廃止されると、その宣言は指定されたプラットフォームまたは言語から削除され、使用できなくなります。 次の形式になりobsoleted: <#versionnumber#>バージョン番号は、ピリオドで区切られた 1 ~ 3 個の正の整数で構成されます。- The
noasyncargument indicates that the declared symbol can’t be used directly in an asynchronous context.
Because Swift concurrency can resume on a different thread after a potential suspension point, using elements like thread-local storage, locks, mutexes, or semaphores across suspension points can lead to incorrect results.
To avoid this problem, add an@available(*, noasync)attribute to the symbol’s declaration:extension pthread_mutex_t { @available(*, noasync) mutating func lock() { pthread_mutex_lock(&self) } @available(*, noasync) mutating func unlock() { pthread_mutex_unlock(&self) } }
This attribute raises a compile-time error when someone uses the symbol in an asynchronous context. You can also use the message argument to provide additional information about the symbol.@available(*, noasync, message: "Migrate locks to Swift concurrency.") mutating func lock() { pthread_mutex_lock(&self) }
If you can guarantee that your code uses a potentially unsafe symbol in a safe manner, you can wrap it in a synchronous function and call that function from an asynchronous context.// Provide a synchronous wrapper around methods with a noasync declaration. extension pthread_mutex_t { mutating func withLock(_ operation: () -> ()) { self.lock() operation() self.unlock() } } func downloadAndStore(key: Int, dataStore: MyKeyedStorage, dataLock: inout pthread_mutex_t) async { // Safely call the wrapper in an asynchronous context. dataLock.withLock { dataStore[key] = downloadContent() } }
You can use the noasync argument on most declarations; however, you can’t use it when declaring deinitializers. Swift must be able to call a class’s deinitializers from any context, both synchronous and asynchronous. noasync引数は、宣言されたシンボルが非同期コンテキストで直接使用できないことを示します。
Swift の並行処理は、潜在的なサスペンドポイントの後に別のスレッドで再開される可能性があるため、スレッドローカルストレージ、ロック、ミューテックス、セマフォなどの要素をサスペンドポイント間で使用すると、誤った結果が生じる可能性があります。
この問題を回避するには、シンボルの宣言に@available(*, noasync)属性を追加します。extension pthread_mutex_t { @available(*, noasync) mutating func lock() { pthread_mutex_lock(&self) } @available(*, noasync) mutating func unlock() { pthread_mutex_unlock(&self) } }
この属性は、シンボルが非同期コンテキストで使用された場合にコンパイル時エラーを発生させます。また、message引数を使用して、シンボルに関する追加情報を提供することもできます。@available(*, noasync, message: "Migrate locks to Swift concurrency.") mutating func lock() { pthread_mutex_lock(&self) }
コードが安全でない可能性のあるシンボルを安全に使用していることを保証できる場合は、そのシンボルを同期関数でラップし、その関数を非同期コンテキストから呼び出すことができます。// Provide a synchronous wrapper around methods with a noasync declaration. extension pthread_mutex_t { mutating func withLock(_ operation: () -> ()) { self.lock() operation() self.unlock() } } func downloadAndStore(key: Int, dataStore: MyKeyedStorage, dataLock: inout pthread_mutex_t) async { // Safely call the wrapper in an asynchronous context. dataLock.withLock { dataStore[key] = downloadContent() } }noasync引数はほとんどの宣言で使用できますが、デイニシャライザの宣言では使用できません。Swift は、同期・非同期を問わず、あらゆるコンテキストからクラスのデイニシャライザを呼び出せるようにする必要があります。- The
messageargument provides a textual message that the compiler displays when emitting a warning or error about the use of a deprecated or obsoleted declaration. It has the following form:message: <#message#>The message consists of a string literal. message引数は、非推奨または廃止された宣言の使用に関する警告またはエラーを生成するときにコンパイラが表示するテキスト メッセージを提供します。 次の形式になりmessage: <#message#>メッセージは文字列リテラルで構成されます。- The
renamedargument provides a textual message that indicates the new name for a declaration that’s been renamed. The compiler displays the new name when emitting an error about the use of a renamed declaration. It has the following form:renamed: <#new name#>The new name consists of a string literal.You can apply theavailableattribute with therenamedandunavailablearguments to a type alias declaration, as shown below, to indicate that the name of a declaration changed between releases of a framework or library. This combination results in a compile-time error that the declaration has been renamed.// First release protocol MyProtocol { // protocol definition }// Subsequent release renames MyProtocol protocol MyRenamedProtocol { // protocol definition } @available(*, unavailable, renamed: "MyRenamedProtocol") typealias MyProtocol = MyRenamedProtocol renamed引数は、名前が変更された宣言の新しい名前を示すテキスト メッセージを提供します。 コンパイラは、名前変更された宣言の使用に関するエラーを生成するときに、新しい名前を表示します。 これは次の形式になりrenamed: <#new name#>新しい名前は文字列リテラルで構成されます。以下に示すように、renamed引数およびunavailable引数を持つavailable属性を型エイリアス宣言に適用して、名前が変更されたことを示すことができます。 フレームワークまたはライブラリのリリース間で変更された宣言。 この組み合わせにより、宣言の名前が変更されたというコンパイル時エラーが発生します。// First release protocol MyProtocol { // protocol definition }// Subsequent release renames MyProtocol protocol MyRenamedProtocol { // protocol definition } @available(*, unavailable, renamed: "MyRenamedProtocol") typealias MyProtocol = MyRenamedProtocol
You can apply multiple available attributes on a single declaration to specify the declaration’s availability on different platforms and different versions of Swift. The declaration that the available attribute applies to is ignored if the attribute specifies a platform or language version that doesn’t match the current target. If you use multiple available attributes, the effective availability is the combination of the platform and Swift availabilities.
単一の宣言に複数のavailable属性を適用して、さまざまなプラットフォームやさまざまなバージョンの Swift で宣言が利用できるかどうかを指定できます。 現在のターゲットと一致しないプラットフォームまたは言語バージョンが属性で指定されている場合、available 属性が適用される宣言は無視されます。 複数のavailable属性を使用する場合、有効な可用性はプラットフォームと Swift の可用性の組み合わせになります。
If an available attribute only specifies an introduced argument in addition to a platform or language name argument, you can use the following shorthand syntax instead:
available属性で、プラットフォーム名または言語名の引数に加えてintroduced引数のみを指定する場合は、代わりに次の短縮構文を使用できます。
@available(<#platform name#> <#version number#>, *)
@available(swift <#version number#>)
The shorthand syntax for available attributes concisely expresses availability for multiple platforms. Although the two forms are functionally equivalent, the shorthand form is preferred whenever possible.
available 属性の短縮構文は、複数のプラットフォームでの可用性を簡潔に表します。 2 つの形式は機能的には同等ですが、可能な限り省略形式が推奨されます。
@available(iOS 10.0, macOS 10.12, *)
class MyClass {
// class definition
}
An available attribute that specifies availability using a Swift version number can’t additionally specify a declaration’s platform availability. Instead, use separate available attributes to specify a Swift version availability and one or more platform availabilities.
Swift バージョン番号を使用して可用性を指定する available 属性では、宣言のプラットフォームの可用性を追加で指定することはできません。 代わりに、個別のavailable属性を使用して、Swift バージョンの可用性と 1 つ以上のプラットフォームの可用性を指定します。
@available(swift 3.0.2)
@available(macOS 10.12, *)
struct MyStruct {
// struct definition
}
backDeployed
戻る展開済み
Apply this attribute to a function, method, subscript, or computed property to include a copy of the symbol’s implementation in programs that call or access the symbol. You use this attribute to annotate symbols that ship as part of a platform, like the APIs that are included with an operating system. This attribute marks symbols that can be made available retroactively by including a copy of their implementation in programs that access them. Copying the implementation is also known as emitting into the client.
この属性を関数、メソッド、添字、または計算プロパティに適用すると、シンボルを呼び出すかアクセスするプログラムにシンボルの実装のコピーが組み込まれます。 この属性は、オペレーティング システムに含まれる API など、プラットフォームの一部として提供されるシンボルに注釈を付けるために使用します。 この属性は、シンボルにアクセスするプログラムにその実装のコピーを含めることによって、遡って使用できるようにできるシンボルをマークします。 実装のコピーは、クライアントへの出力とも呼ばれます。
This attribute takes a before: argument, specifying the first version of platforms that provide this symbol. These platform versions have the same meaning as the platform version you specify for the available attribute. Unlike the available attribute, the list can’t contain an asterisk (*) to refer to all versions. For example, consider the following code:
この属性は before: 引数を受け取り、このシンボルを提供するプラットフォームの最初のバージョンを指定します。 これらのプラットフォーム バージョンは、available属性に指定したプラットフォーム バージョンと同じ意味を持ちます。 available属性とは異なり、リストにはすべてのバージョンを参照するアスタリスク (* ) を含めることはできません。 たとえば、次のコードを考えてみましょう。
@available(iOS 16, *)
@backDeployed(before: iOS 17)
func someFunction() { /* ... */ }
In the example above, the iOS SDK provides someFunction() starting in iOS 17. In addition, the SDK makes someFunction() available on iOS 16 using back deployment.
上の例では、iOS SDK は iOS 17 以降で someFunction() を提供します。さらに、SDK はバック デプロイメントを使用して iOS 16 で someFunction() を利用できるようにします。
When compiling code that calls this function, Swift inserts a layer of indirection that finds the function’s implementation. If the code is run using a version of the SDK that includes this function, the SDK’s implementation is used. Otherwise, the copy included in the caller is used. In the example above, calling someFunction() uses the implementation from the SDK when running on iOS 17 or later, and when running on iOS 16 it uses the copy of someFunction() that’s included in the caller.
この関数を呼び出すコードをコンパイルするとき、Swift は関数の実装を見つける間接層を挿入します。 この関数を含む SDK のバージョンを使用してコードが実行される場合は、SDK の実装が使用されます。 それ以外の場合は、呼び出し元に含まれるコピーが使用されます。 上の例では、someFunction() の呼び出しでは、iOS 17 以降で実行する場合は SDK の実装が使用され、iOS 16 で実行する場合は呼び出し元に含まれる someFunction() のコピーが使用されます。
Note
注釈
When the caller’s minimum deployment target is the same as or greater than the first version of the SDK that includes the symbol, the compiler can optimize away the runtime check and call the SDK’s implementation directly. In this case, if you access the back-deployed symbol directly, the compiler can also omit the copy of the symbol’s implementation from the client.
呼び出し元の最小デプロイメント ターゲットが、シンボルを含む SDK の最初のバージョンと同じかそれ以上の場合、コンパイラーはランタイム チェックを最適化して SDK の実装を直接呼び出すことができます。 この場合、バックデプロイされたシンボルに直接アクセスすると、コンパイラはクライアントからのシンボル実装のコピーを省略することもできます。
Functions, methods, subscripts, and computed properties that meet the following criteria can be back deployed:
次の基準を満たす関数、メソッド、添字、および計算されたプロパティは、バック デプロイできます。
- The declaration is
publicor@usableFromInline. - 宣言は
publicまたは@usableFromInlineです。 - For class instance methods and class type methods, the method is marked
finaland isn’t marked@objc. - クラス インスタンス メソッドとクラス 型 メソッドの場合、メソッドは「
final」とマークされ、「@objc」とはマークされません。 - The implementation satisfies the requirements for an inlinable function, described in inlinable.
- この実装は、「
inlinable」で説明されているインライン可能関数の要件を満たしています。
discardableResult
破棄可能な結果
Apply this attribute to a function or method declaration to suppress the compiler warning when the function or method that returns a value is called without using its result.
この属性を関数またはメソッドの宣言に適用すると、値を返す関数またはメソッドがその結果を使用せずに呼び出されたときのコンパイラ警告が抑制されます。
dynamicCallable
動的呼び出し可能
Apply this attribute to a class, structure, enumeration, or protocol to treat instances of the type as callable functions. The type must implement either a dynamicallyCall(withArguments:) method, a dynamicallyCall(withKeywordArguments:) method, or both.
この属性をクラス、構造体、列挙、またはプロトコルに適用して、その型のインスタンスを呼び出し可能な関数として扱います。 この型は、dynamicallyCall(withArguments:) メソッド、dynamicallyCall(withKeywordArguments:) メソッド、またはその両方を実装する必要があります。
You can call an instance of a dynamically callable type as if it’s a function that takes any number of arguments.
動的に呼び出し可能な型のインスタンスは、任意の数の引数を取る関数であるかのように呼び出すことができます。
@dynamicCallable
struct TelephoneExchange {
func dynamicallyCall(withArguments phoneNumber: [Int]) {
if phoneNumber == [4, 1, 1] {
print("Get Swift help on forums.swift.org")
} else {
print("Unrecognized number")
}
}
}
let dial = TelephoneExchange()
// Use a dynamic method call.
dial(4, 1, 1)
// Prints "Get Swift help on forums.swift.org"
dial(8, 6, 7, 5, 3, 0, 9)
// Prints "Unrecognized number"
// Call the underlying method directly.
dial.dynamicallyCall(withArguments: [4, 1, 1])
The declaration of the dynamicallyCall(withArguments:) method must have a single parameter that conforms to the ExpressibleByArrayLiteral(Link:developer.apple.com) protocol — like [Int] in the example above. The return type can be any type.
dynamicallyCall(withArguments:) メソッドの宣言には、ExpressibleByArrayLiteral (Link:developer.apple.com)(英語)プロトコルに準拠する単一のパラメータが必要です(上の例の [Int] など)。 戻り値の型は任意の型にすることができます。
You can include labels in a dynamic method call if you implement the dynamicallyCall(withKeywordArguments:) method.
dynamicallyCall(withKeywordArguments:) メソッドを実装する場合は、動的メソッド呼び出しにラベルを含めることができます。
@dynamicCallable
struct Repeater {
func dynamicallyCall(withKeywordArguments pairs: KeyValuePairs<String, Int>) -> String {
return pairs
.map { label, count in
repeatElement(label, count: count).joined(separator: " ")
}
.joined(separator: "\n")
}
}
let repeatLabels = Repeater()
print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1))
// a
// b b
// c c c
// b b
// a
The declaration of the dynamicallyCall(withKeywordArguments:) method must have a single parameter that conforms to the ExpressibleByDictionaryLiteral(Link:developer.apple.com) protocol, and the return type can be any type. The parameter’s Key(Link:developer.apple.com) must be ExpressibleByStringLiteral(Link:developer.apple.com). The previous example uses KeyValuePairs(Link:developer.apple.com) as the parameter type so that callers can include duplicate parameter labels — a and b appear multiple times in the call to repeat.
dynamicallyCall(withKeywordArguments:) メソッドの宣言には、 (Link:developer.apple.com)(英語)プロトコルに準拠する単一のパラメータが必要で、戻り値の型は任意の型にすることができます。 パラメータのExpressibleByDictionaryLiteral(Link:developer.apple.com)(英語)は Key(Link:developer.apple.com)(英語) である必要があります。 前の例では、ExpressibleByStringLiteral(Link:developer.apple.com) (英語)をパラメータ タイプとして使用しているため、発信者は重複したパラメータ ラベルを含めることができます。KeyValuePairsa と b はrepeatの呼び出し内で複数回表示されます。
If you implement both dynamicallyCall methods, dynamicallyCall(withKeywordArguments:) is called when the method call includes keyword arguments. In all other cases, dynamicallyCall(withArguments:) is called.
両方の dynamicallyCall メソッドを実装すると、メソッド呼び出しにキーワード引数が含まれるときに dynamicallyCall(withKeywordArguments:) が呼び出されます。 それ以外の場合はすべて、dynamicallyCall(withArguments:) が呼び出されます。
You can only call a dynamically callable instance with arguments and a return value that match the types you specify in one of your dynamicallyCall method implementations. The call in the following example doesn’t compile because there isn’t an implementation of dynamicallyCall(withArguments:) that takes KeyValuePairs<String, String>.
動的に呼び出し可能なインスタンスは、dynamicallyCall メソッドの実装の 1 つで指定した型と一致する引数と戻り値でのみ呼び出すことができます。 を受け取る KeyValuePairs<String, String>dynamicallyCall(withArguments:) の実装がないため、次の例の呼び出しはコンパイルされません。
repeatLabels(a: "four") // Error
dynamicMemberLookup
動的メンバー検索
Apply this attribute to a class, structure, enumeration, or protocol to enable members to be looked up by name at runtime. The type must implement a subscript(dynamicMember:) subscript.
この属性をクラス、構造体、列挙、またはプロトコルに適用すると、実行時にメンバーを名前で検索できるようになります。 この型は、subscript(dynamicMember:) サブスクリプトを実装する必要があります。
In an explicit member expression, if there isn’t a corresponding declaration for the named member, the expression is understood as a call to the type’s subscript(dynamicMember:) subscript, passing information about the member as the argument. The subscript can accept a parameter that’s either a key path or a member name; if you implement both subscripts, the subscript that takes key path argument is used.
明示的なメンバー式では、名前付きメンバーに対応する宣言がない場合、式は型のsubscript(dynamicMember:)添字への呼び出しとして理解され、メンバーに関する情報が引数として渡されます。 添え字はキー パスまたはメンバー名のいずれかのパラメーターを受け入れることができます。 両方の添え字を実装した場合は、キー パス引数を取る添え字が使用されます。
An implementation of subscript(dynamicMember:) can accept key paths using an argument of type KeyPath(Link:developer.apple.com), WritableKeyPath(Link:developer.apple.com), or ReferenceWritableKeyPath(Link:developer.apple.com). It can accept member names using an argument of a type that conforms to the ExpressibleByStringLiteral(Link:developer.apple.com) protocol — in most cases, String. The subscript’s return type can be any type.
subscript(dynamicMember:) の実装は、KeyPath(Link:developer.apple.com)(英語)、WritableKeyPath(Link:developer.apple.com)(英語)、または ReferenceWritableKeyPath(Link:developer.apple.com)(英語) 型の引数を使用してキーパスを受け入れることができます。 ExpressibleByStringLiteral(Link:developer.apple.com)(英語) プロトコルに準拠する型の引数 (ほとんどの場合、String) を使用してメンバー名を受け入れることができます。 添字の戻り値の型は任意の型にすることができます。
Dynamic member lookup by member name can be used to create a wrapper type around data that can’t be type checked at compile time, such as when bridging data from other languages into Swift. For example:
メンバー名による動的メンバー検索を使用すると、他の言語から Swift にデータをブリッジする場合など、コンパイル時に型チェックできないデータの周囲にラッパー型を作成できます。 例えば:
@dynamicMemberLookup
struct DynamicStruct {
let dictionary = ["someDynamicMember": 325,
"someOtherMember": 787]
subscript(dynamicMember member: String) -> Int {
return dictionary[member] ?? 1054
}
}
let s = DynamicStruct()
// Use dynamic member lookup.
let dynamic = s.someDynamicMember
print(dynamic)
// Prints "325"
// Call the underlying subscript directly.
let equivalent = s[dynamicMember: "someDynamicMember"]
print(dynamic == equivalent)
// Prints "true"
Dynamic member lookup by key path can be used to implement a wrapper type in a way that supports compile-time type checking. For example:
キー パスによる動的メンバー検索を使用すると、コンパイル時の型チェックをサポートする方法でラッパー型を実装できます。 例えば:
struct Point { var x, y: Int }
@dynamicMemberLookup
struct PassthroughWrapper<Value> {
var value: Value
subscript<T>(dynamicMember member: KeyPath<Value, T>) -> T {
get { return value[keyPath: member] }
}
}
let point = Point(x: 381, y: 431)
let wrapper = PassthroughWrapper(value: point)
print(wrapper.x)
freestanding
自立型
Apply the freestanding attribute to the declaration of a freestanding macro.
独立したマクロの宣言にfreestanding属性を適用します。
frozen
凍結
Apply this attribute to a structure or enumeration declaration to restrict the kinds of changes you can make to the type. This attribute is allowed only when compiling in library evolution mode. Future versions of the library can’t change the declaration by adding, removing, or reordering an enumeration’s cases or a structure’s stored instance properties. These changes are allowed on nonfrozen types, but they break ABI compatibility for frozen types.
この属性を構造体または列挙型の宣言に適用して、型に加えられる変更の種類を制限します。 この属性は、ライブラリ進化モードでコンパイルする場合にのみ許可されます。 ライブラリの将来のバージョンでは、列挙型のケースや構造体の格納されたインスタンス プロパティを追加、削除、並べ替えることによって宣言を変更することはできません。 これらの変更は非凍結型では許可されますが、凍結型の ABI 互換性は失われます。
Note
注釈
When the compiler isn’t in library evolution mode, all structures and enumerations are implicitly frozen, and this attribute is ignored.
コンパイラがライブラリ進化モードではない場合、すべての構造体と列挙型は暗黙的に凍結され、この属性は無視されます。
In library evolution mode, code that interacts with members of nonfrozen structures and enumerations is compiled in a way that allows it to continue working without recompiling even if a future version of the library adds, removes, or reorders some of that type’s members. The compiler makes this possible using techniques like looking up information at runtime and adding a layer of indirection. Marking a structure or enumeration as frozen gives up this flexibility to gain performance: Future versions of the library can make only limited changes to the type, but the compiler can make additional optimizations in code that interacts with the type’s members.
ライブラリ進化モードでは、凍結されていない構造体および列挙型のメンバーと対話するコードは、ライブラリの将来のバージョンでその型のメンバーの一部が追加、削除、または並べ替えられた場合でも、再コンパイルせずに動作し続けることができる方法でコンパイルされます。 コンパイラは、実行時の情報の検索や間接層の追加などの手法を使用してこれを可能にします。 構造体または列挙型を凍結としてマークすると、パフォーマンスを向上させるためにこの柔軟性が失われます。ライブラリの将来のバージョンでは、型に対して限定的な変更のみを行うことができますが、コンパイラは型のメンバーと対話するコードで追加の最適化を行うことができます。
Frozen types, the types of the stored properties of frozen structures, and the associated values of frozen enumeration cases must be public or marked with the usableFromInline attribute. The properties of a frozen structure can’t have property observers, and expressions that provide the initial value for stored instance properties must follow the same restrictions as inlinable functions, as discussed in inlinable.
凍結されたタイプ、凍結された構造の保存されたプロパティのタイプ、および凍結された列挙ケースの関連値はパブリックであるか、usableFromInline 属性でマークされている必要があります。 凍結された構造のプロパティはプロパティ オブザーバーを持つことができず、ストアド インスタンス プロパティの初期値を提供する式は、インライン可能で説明したように、インライン可能関数と同じ制限に従う必要があります。
To enable library evolution mode on the command line, pass the -enable-library-evolution option to the Swift compiler. To enable it in Xcode, set the “Build Libraries for Distribution” build setting (BUILD_LIBRARY_FOR_DISTRIBUTION) to Yes, as described in Xcode Help.
コマンドラインでライブラリ進化モードを有効にするには、-enable-library-evolution オプションを Swift コンパイラーに渡します。 Xcode でこれを有効にするには、Xcode ヘルプの説明に従って、「配布用ライブラリのビルド」ビルド設定 (BUILD_LIBRARY_FOR_DISTRIBUTION) を Yes に設定します。
A switch statement over a frozen enumeration doesn’t require a default case, as discussed in Switching Over Future Enumeration Cases. Including a default or @unknown default case when switching over a frozen enumeration produces a warning because that code is never executed.
「今後の列挙ケースの切り替え」で説明されているように、凍結された列挙に対する switch ステートメントにはdefaultのケースは必要ありません。 凍結された列挙を切り替えるときに defaultまたは @unknown defaultのケースを含めると、そのコードは実行されないため、警告が生成されます。
GKInspectable
GK検査可能
Apply this attribute to expose a custom GameplayKit component property to the SpriteKit editor UI. Applying this attribute also implies the objc attribute.
この属性を適用して、カスタム GameplayKit コンポーネント プロパティを SpriteKit エディター UI に公開します。 この属性を適用すると、objc 属性も暗黙的に適用されます。
inlinable
インライン化可能
Apply this attribute to a function, method, computed property, subscript, convenience initializer, or deinitializer declaration to expose that declaration’s implementation as part of the module’s public interface. The compiler is allowed to replace calls to an inlinable symbol with a copy of the symbol’s implementation at the call site.
この属性を関数、メソッド、計算プロパティ、添字、コンビニエンス イニシャライザ、またはディイニシャライザの宣言に適用して、その宣言の実装をモジュールのパブリック インターフェイスの一部として公開します。 コンパイラは、インライン化可能なシンボルへの呼び出しを、呼び出しサイトでのシンボルの実装のコピーに置き換えることができます。
Inlinable code can interact with public symbols declared in any module, and it can interact with internal symbols declared in the same module that are marked with the usableFromInline attribute. Inlinable code can’t interact with private or fileprivate symbols.
インライン化可能なコードは、任意のモジュールで宣言されたpublic シンボルと対話することができ、同じモジュールで宣言され、usableFromInline 属性でマークされたinternalシンボルと対話することもできます。 インライン化可能なコードは、private シンボルまたはfileprivate シンボルを操作できません。
This attribute can’t be applied to declarations that are nested inside functions or to fileprivate or private declarations. Functions and closures that are defined inside an inlinable function are implicitly inlinable, even though they can’t be marked with this attribute.
この属性は、関数内にネストされている宣言や、fileprivate 宣言や private 宣言には適用できません。 インライン化可能な関数内で定義された関数とクロージャは、この属性でマークすることはできませんが、暗黙的にインライン化可能です。
main
メイン
Apply this attribute to a structure, class, or enumeration declaration to indicate that it contains the top-level entry point for program flow. The type must provide a main type function that doesn’t take any arguments and returns Void. For example:
この属性を構造体、クラス、または列挙宣言に適用して、プログラム フローの最上位のエントリ ポイントが含まれていることを示します。 この型は、引数をとらずに Void を返す main 型関数を提供する必要があります。 例えば:
@main
struct MyTopLevel {
static func main() {
// Top-level code goes here
}
}
Another way to describe the requirements of the main attribute is that the type you write this attribute on must satisfy the same requirements as types that conform to the following hypothetical protocol:
main 属性の要件を説明するもう 1 つの方法は、この属性を書き込む型は、次の仮想プロトコルに準拠する型と同じ要件を満たさなければならないということです。
protocol ProvidesMain {
static func main() throws
}
The Swift code you compile to make an executable can contain at most one top-level entry point, as discussed in Top-Level Code.
「トップレベルのコード」で説明したように、実行可能ファイルを作成するためにコンパイルする Swift コードには、トップレベルのエントリ ポイントを 1 つだけ含めることができます。
nonobjc
非オブジェクト
Apply this attribute to a method, property, subscript, or initializer declaration to suppress an implicit objc attribute. The nonobjc attribute tells the compiler to make the declaration unavailable in Objective-C code, even though it’s possible to represent it in Objective-C.
この属性をメソッド、プロパティ、添字、またはイニシャライザ宣言に適用して、暗黙的な objc 属性を抑制します。 nonobjc 属性は、宣言を Objective-C で表現できる場合でも、Objective-C コードでは宣言を使用できないようにコンパイラーに指示します。
Applying this attribute to an extension has the same effect as applying it to every member of that extension that isn’t explicitly marked with the objc attribute.
この属性を拡張機能に適用すると、その拡張機能の objc 属性で明示的にマークされていないすべてのメンバーに適用するのと同じ効果があります。
You use the nonobjc attribute to resolve circularity for bridging methods in a class marked with the objc attribute, and to allow overloading of methods and initializers in a class marked with the objc attribute.
nonobjc 属性を使用すると、objc 属性でマークされたクラス内のブリッジング メソッドの循環性を解決し、objc 属性でマークされたクラス内のメソッドとイニシャライザのオーバーロードを許可できます。
A method marked with the nonobjc attribute can’t override a method marked with the objc attribute. However, a method marked with the objc attribute can override a method marked with the nonobjc attribute. Similarly, a method marked with the nonobjc attribute can’t satisfy a protocol requirement for a method marked with the objc attribute.
nonobjc 属性でマークされたメソッドは、objc 属性でマークされたメソッドをオーバーライドできません。 ただし、objc 属性でマークされたメソッドは、nonobjc 属性でマークされたメソッドをオーバーライドできます。 同様に、nonobjc 属性でマークされたメソッドは、objc 属性でマークされたメソッドのプロトコル要件を満たすことができません。
NSApplicationMain
NSアプリケーションメイン
Deprecated
廃止
This attribute is deprecated; use the main attribute instead. In Swift 6, using this attribute will be an error.
この属性は非推奨です。 代わりに main 属性を使用してください。 Swift 6 では、この属性を使用するとエラーになります。
Apply this attribute to a class to indicate that it’s the application delegate. Using this attribute is equivalent to calling the NSApplicationMain(_:_:) function.
この属性をクラスに適用して、それがアプリケーション デリゲートであることを示します。 この属性を使用することは、NSApplicationMain(::) 関数を呼び出すことと同じです。
If you don’t use this attribute, supply a main.swift file with code at the top level that calls the NSApplicationMain(_:_:) function as follows:
この属性を使用しない場合は、次のように NSApplicationMain(::) 関数を呼び出すコードを最上位に含む main.swift ファイルを指定します。
import AppKit
NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
The Swift code you compile to make an executable can contain at most one top-level entry point, as discussed in Top-Level Code.
「トップレベルのコード」で説明したように、実行可能ファイルを作成するためにコンパイルする Swift コードには、トップレベルのエントリ ポイントを 1 つだけ含めることができます。
NSCopying
NSコピー
Apply this attribute to a stored variable property of a class. This attribute causes the property’s setter to be synthesized with a copy of the property’s value — returned by the copyWithZone(_:) method — instead of the value of the property itself. The type of the property must conform to the NSCopying protocol.
この属性をクラスのストアド変数プロパティに適用します。 この属性により、プロパティのセッターは、プロパティ自体の値ではなく、copyWithZone(_:) メソッドによって返されたプロパティ値のコピーを使用して合成されます。 プロパティのタイプは NSCopying プロトコルに準拠する必要があります。
The NSCopying attribute behaves in a way similar to the Objective-C copy property attribute.
NSCopying 属性は、Objective-C のcopy プロパティ属性と同様に動作します。
NSManaged
NSマネージド
Apply this attribute to an instance method or stored variable property of a class that inherits from NSManagedObject to indicate that Core Data dynamically provides its implementation at runtime, based on the associated entity description. For a property marked with the NSManaged attribute, Core Data also provides the storage at runtime. Applying this attribute also implies the objc attribute.
この属性を NSManagedObject から継承するクラスのインスタンス メソッドまたはストアド変数プロパティに適用して、関連するエンティティの説明に基づいて Core Data が実行時にその実装を動的に提供することを示します。 NSManaged 属性でマークされたプロパティの場合、Core Data は実行時にストレージも提供します。 この属性を適用すると、objc 属性も暗黙的に適用されます。
objc
objc
Apply this attribute to any declaration that can be represented in Objective-C — for example, nonnested classes, protocols, nongeneric enumerations (constrained to integer raw-value types), properties and methods (including getters and setters) of classes, protocols and optional members of a protocol, initializers, and subscripts. The objc attribute tells the compiler that a declaration is available to use in Objective-C code.
この属性は、Objective-C で表現できる任意の宣言に適用します。たとえば、ネストされていないクラス、プロトコル、非ジェネリック列挙型 (生の整数値型に制限)、クラス、プロトコル、オプションのプロパティとメソッド (ゲッターとセッターを含む) です。 プロトコルのメンバー、イニシャライザ、およびサブスクリプト。 objc 属性は、宣言が Objective-C コードで使用できることをコンパイラーに伝えます。
Applying this attribute to an extension has the same effect as applying it to every member of that extension that isn’t explicitly marked with the nonobjc attribute.
この属性を拡張機能に適用すると、nonobjc 属性で明示的にマークされていない拡張機能のすべてのメンバーに適用するのと同じ効果があります。
The compiler implicitly adds the objc attribute to subclasses of any class defined in Objective-C. However, the subclass must not be generic, and must not inherit from any generic classes. You can explicitly add the objc attribute to a subclass that meets these criteria, to specify its Objective-C name as discussed below. Protocols that are marked with the objc attribute can’t inherit from protocols that aren’t marked with this attribute.
コンパイラは、Objective-C で定義されたクラスのサブクラスに objc 属性を暗黙的に追加します。 ただし、サブクラスはジェネリックであってはならず、ジェネリック クラスを継承してはなりません。 これらの基準を満たすサブクラスに objc 属性を明示的に追加して、以下で説明するように Objective-C 名を指定できます。 objc 属性でマークされたプロトコルは、この属性でマークされていないプロトコルを継承できません。
The objc attribute is also implicitly added in the following cases:
objc 属性は、次の場合にも暗黙的に追加されます。
- The declaration is an override in a subclass, and the superclass’s declaration has the
objcattribute. - この宣言はサブクラスのオーバーライドであり、スーパークラスの宣言には
objc属性があります。 - The declaration satisfies a requirement from a protocol that has the
objcattribute. - この宣言は、
objc属性を持つプロトコルの要件を満たします。 - The declaration has the
IBAction,IBSegueAction,IBOutlet,IBDesignable,IBInspectable,NSManaged, orGKInspectableattribute. - 宣言には、
IBAction、IBSegueAction、IBOutlet、IBDesignable、IBInspectable、NSManated、またはGKInspectable属性があります。
If you apply the objc attribute to an enumeration, each enumeration case is exposed to Objective-C code as the concatenation of the enumeration name and the case name. The first letter of the case name is capitalized. For example, a case named venus in a Swift Planet enumeration is exposed to Objective-C code as a case named PlanetVenus.
objc 属性を列挙型に適用すると、各列挙型ケースは列挙型名とケース名の連結として Objective-C コードに公開されます。 ケース名の最初の文字は大文字になります。 たとえば、Swift Planet 列挙内の venus という名前のケースは、PlanetVenus という名前のケースとして Objective-C コードに公開されます。
The objc attribute optionally accepts a single attribute argument, which consists of an identifier. The identifier specifies the name to be exposed to Objective-C for the entity that the objc attribute applies to. You can use this argument to name classes, enumerations, enumeration cases, protocols, methods, getters, setters, and initializers. If you specify the Objective-C name for a class, protocol, or enumeration, include a three-letter prefix on the name, as described in Conventions(Link:developer.apple.com) in Programming with Objective-C(Link:developer.apple.com). The example below exposes the getter for the enabled property of the ExampleClass to Objective-C code as isEnabled rather than just as the name of the property itself.
objc 属性は、オプションで、識別子で構成される単一の属性引数を受け入れます。 識別子は、objc 属性が適用されるエンティティの Objective-C に公開される名前を指定します。 この引数を使用して、クラス、列挙、列挙ケース、プロトコル、メソッド、ゲッター、セッター、および初期化子に名前を付けることができます。 クラス、プロトコル、または列挙型の Objective-C 名を指定する場合は、「Objective-Cでのプログラミング(Link:developer.apple.com)(英語)」の「規則(Link:developer.apple.com)(英語)」で説明されているように、名前に 3 文字の接頭辞を含めます。 以下の例では、ExampleClass のenabledプロパティのゲッターを、プロパティ自体の名前としてではなく isEnabled として Objective-C コードに公開しています。
class ExampleClass: NSObject {
@objc var enabled: Bool {
@objc(isEnabled) get {
// Return the appropriate value
}
}
}
For more information, see Importing Swift into Objective-C(Link:developer.apple.com).
詳細については、「Objective-C への Swift のインポート(Link:developer.apple.com)(英語)」を参照してください。
Note
注釈
The argument to the objc attribute can also change the runtime name for that declaration. You use the runtime name when calling functions that interact with the Objective-C runtime, like NSClassFromString(_:)(Link:developer.apple.com), and when specifying class names in an app’s Info.plist file. If you specify a name by passing an argument, that name is used as the name in Objective-C code and as the runtime name. If you omit the argument, the name used in Objective-C code matches the name in Swift code, and the runtime name follows the normal Swift compiler convention of name mangling.
objc 属性の引数は、その宣言のランタイム名を変更することもできます。 ランタイム名は、NSClassFromString(_:)(Link:developer.apple.com)(英語) などの Objective-C ランタイムと対話する関数を呼び出すとき、およびアプリの Info.plist ファイルでクラス名を指定するときに使用します。 引数を渡して名前を指定すると、その名前は Objective-C コード内の名前およびランタイム名として使用されます。 引数を省略した場合、Objective-C コードで使用される名前は Swift コードの名前と一致し、ランタイム名は通常の Swift コンパイラの名前マングリング規則に従います。
objcMembers
objcメンバー
Apply this attribute to a class declaration, to implicitly apply the objc attribute to all Objective-C compatible members of the class, its extensions, its subclasses, and all of the extensions of its subclasses.
この属性をクラス宣言に適用すると、クラスのすべての Objective-C 互換メンバー、その拡張機能、そのサブクラス、およびそのサブクラスのすべての拡張機能に objc 属性が暗黙的に適用されます。
Most code should use the objc attribute instead, to expose only the declarations that are needed. If you need to expose many declarations, you can group them in an extension that has the objc attribute. The objcMembers attribute is a convenience for libraries that make heavy use of the introspection facilities of the Objective-C runtime. Applying the objc attribute when it isn’t needed can increase your binary size and adversely affect performance.
ほとんどのコードでは、代わりに objc 属性を使用して、必要な宣言のみを公開する必要があります。 多くの宣言を公開する必要がある場合は、objc 属性を持つ拡張機能に宣言をグループ化できます。 objcMembers 属性は、Objective-C ランタイムのイントロスペクション機能を多用するライブラリにとって便利です。 不要なときに objc 属性を適用すると、バイナリ サイズが増加し、パフォーマンスに悪影響を及ぼす可能性があります。
↓6.0
preconcurrency
同時実行前
Apply this attribute to a declaration, to suppress strict concurrency checking. You can apply this attribute to the following kinds of declarations:
厳密な同時実行チェックを抑制するには、この属性を宣言に適用します。この属性は、次の種類の宣言に適用できます。
- Imports
- Structures, classes, and actors
- Enumerations and enumeration cases
- Protocols
- Variables and constants
- Subscripts
- Initializers
- Functions
On an import declaration, this attribute reduces the strictness of concurrency checking for code that uses types from the imported module. Specifically, types from the imported module that aren’t explicitly marked as nonsendable can be used in a context that requires sendable types.
インポート宣言では、この属性により、インポートされたモジュールの型を使用するコードの同時実行チェックの厳密さが緩和されます。具体的には、送信不可として明示的にマークされていないインポートされたモジュールの型は、送信可能な型を必要とするコンテキストで使用できます。
On other declarations, this attribute reduces the strictness of concurrency checking for code that uses the symbol being declared. When you use this symbol in a scope that has minimal concurrency checking, concurrency-related constraints specified by that symbol, such as Sendable requirements or global actors, aren’t checked.
他の宣言では、この属性により、宣言されているシンボルを使用するコードの同時実行チェックの厳密さが低下します。同時実行チェックが最小限のスコープ内でこのシンボルを使用すると、そのシンボルによって指定される同時実行関連の制約 (Sendable 要件やグローバル アクターなど) はチェックされません。
You can use this attribute as follows, to aid in migrating code to strict concurrency checking:
この属性を次のように使用すると、コードを厳密な同時実行チェックに移行しやすくなります。
- Enable strict checking.
- 厳密なチェックを有効にします。
- Annotate imports with the
preconcurrencyattribute for modules that haven’t enabled strict checking. - 厳密なチェックを有効にしていないモジュールのインポートに、
preconcurrency属性を注釈として付けます。 - After migrating a module to strict checking, remove the
preconcurrencyattribute. The compiler warns you about any places where thepreconcurrencyattribute on an import no longer has an effect and should be removed. - モジュールを厳密なチェックに移行した後、
preconcurrency属性を削除します。インポートのpreconcurrency属性が効力を持たなくなり、削除する必要がある場所があると、コンパイラーによって警告が表示されます。
For other declarations, add the preconcurrency attribute when you add concurrency-related constraints to the declaration, if you still have clients that haven’t migrated to strict checking. Remove the preconcurrency attribute after all your clients have migrated.
その他の宣言では、厳密なチェックに移行していないクライアントがまだある場合は、宣言に同時実行関連の制約を追加するときに、preconcurrency 属性を追加します。すべてのクライアントが移行したら、preconcurrency 属性を削除します。
Declarations from Objective-C are always imported as if they were marked with the preconcurrencyattribute.
Objective-C からの宣言は、常に preconcurrency 属性でマークされているかのようにインポートされます。
↑6.0
propertyWrapper
プロパティラッパー
Apply this attribute to a class, structure, or enumeration declaration to use that type as a property wrapper. When you apply this attribute to a type, you create a custom attribute with the same name as the type. Apply that new attribute to a property of a class, structure, or enumeration to wrap access to the property through an instance of the wrapper type; apply the attribute to a local stored variable declaration to wrap access to the variable the same way. Computed variables, global variables, and constants can’t use property wrappers.
この属性をクラス、構造体、または列挙宣言に適用して、その型をプロパティ ラッパーとして使用します。 この属性を型に適用すると、その型と同じ名前のカスタム属性が作成されます。 その新しい属性をクラス、構造体、または列挙のプロパティに適用して、ラッパー型のインスタンスを介してプロパティへのアクセスをラップします。 この属性をローカルのストアド変数宣言に適用して、同じ方法で変数へのアクセスをラップします。 計算変数、グローバル変数、定数ではプロパティ ラッパーを使用できません。
The wrapper must define a wrappedValue instance property. The wrapped value of the property is the value that the getter and setter for this property expose. In most cases, wrappedValue is a computed value, but it can be a stored value instead. The wrapper defines and manages any underlying storage needed by its wrapped value. The compiler synthesizes storage for the instance of the wrapper type by prefixing the name of the wrapped property with an underscore (_) — for example, the wrapper for someProperty is stored as _someProperty. The synthesized storage for the wrapper has an access control level of private.
ラッパーは、wrappedValue インスタンス プロパティを定義する必要があります。 プロパティのラップされた値は、このプロパティのゲッターとセッターが公開する値です。 ほとんどの場合、wrappedValue は計算された値ですが、代わりに保存された値である場合もあります。 ラッパーは、ラップされた値に必要な基礎となるストレージを定義および管理します。 コンパイラは、ラップされたプロパティの名前の前にアンダースコア (_) を付けることで、ラッパー型のインスタンスのストレージを合成します。たとえば、someProperty のラッパーは _someProperty として保存されます。 ラッパーの合成ストレージのアクセス制御レベルはprivateです。
A property that has a property wrapper can include willSet and didSet blocks, but it can’t override the compiler-synthesized get or set blocks.
プロパティ ラッパーを持つプロパティには、willSet ブロックと didSet ブロックを含めることができますが、コンパイラで合成された get ブロックや set ブロックをオーバーライドすることはできません。
Swift provides two forms of syntactic sugar for initialization of a property wrapper. You can use assignment syntax in the definition of a wrapped value to pass the expression on the right-hand side of the assignment as the argument to the wrappedValue parameter of the property wrapper’s initializer. You can also provide arguments to the attribute when you apply it to a property, and those arguments are passed to the property wrapper’s initializer. For example, in the code below, SomeStruct calls each of the initializers that SomeWrapper defines.
Swift は、プロパティ ラッパーの初期化のために 2 つの形式の糖衣構文を提供します。 ラップされた値の定義で代入構文を使用すると、代入の右側の式を引数としてプロパティ ラッパーのイニシャライザの WrappedValue パラメータに渡すことができます。 属性をプロパティに適用するときに属性に引数を指定することもでき、それらの引数はプロパティ ラッパーのイニシャライザに渡されます。 たとえば、以下のコードでは、SomeStruct は SomeWrapper が定義する各イニシャライザを呼び出します。
@propertyWrapper
struct SomeWrapper {
var wrappedValue: Int
var someValue: Double
init() {
self.wrappedValue = 100
self.someValue = 12.3
}
init(wrappedValue: Int) {
self.wrappedValue = wrappedValue
self.someValue = 45.6
}
init(wrappedValue value: Int, custom: Double) {
self.wrappedValue = value
self.someValue = custom
}
}
struct SomeStruct {
// Uses init()
@SomeWrapper var a: Int
// Uses init(wrappedValue:)
@SomeWrapper var b = 10
// Both use init(wrappedValue:custom:)
@SomeWrapper(custom: 98.7) var c = 30
@SomeWrapper(wrappedValue: 30, custom: 98.7) var d
}
The projected value for a wrapped property is a second value that a property wrapper can use to expose additional functionality. The author of a property wrapper type is responsible for determining the meaning of its projected value and defining the interface that the projected value exposes. To project a value from a property wrapper, define a projectedValue instance property on the wrapper type. The compiler synthesizes an identifier for the projected value by prefixing the name of the wrapped property with a dollar sign ($) — for example, the projected value for someProperty is $someProperty. The projected value has the same access control level as the original wrapped property.
ラップされたプロパティの投影値は、プロパティ ラッパーが追加の機能を公開するために使用できる 2 番目の値です。 プロパティ ラッパー 型の作成者は、その投影値の意味を決定し、投影値が公開するインターフェイスを定義する責任があります。 プロパティ ラッパーから値を投影するには、ラッパー 型で projectedValue (くま注:このプロパティ名は固定です。)インスタンス プロパティを定義します。 コンパイラは、ラップされたプロパティの名前の前にドル記号 ($) を付けることで、投影値の識別子を合成します。たとえば、someProperty の投影値は $someProperty になります。 投影値は、元のラップされたプロパティと同じアクセス制御レベルを持ちます。
@propertyWrapper
struct WrapperWithProjection {
var wrappedValue: Int
var projectedValue: SomeProjection {
return SomeProjection(wrapper: self)
}
}
struct SomeProjection {
var wrapper: WrapperWithProjection
}
struct SomeStruct {
@WrapperWithProjection var x = 123
}
let s = SomeStruct()
s.x // Int value
s.$x // SomeProjection value
s.$x.wrapper // WrapperWithProjection value
resultBuilder
結果ビルダー
Apply this attribute to a class, structure, enumeration to use that type as a result builder. A result builder is a type that builds a nested data structure step by step. You use result builders to implement a domain-specific language (DSL) for creating nested data structures in a natural, declarative way. For an example of how to use the resultBuilder attribute, see Result Builders.
この属性をクラス、構造体、列挙に適用して、その型を結果ビルダーとして使用します。 結果ビルダーは、ネストされたデータ構造を段階的に構築するタイプです。 結果ビルダーを使用して、自然で宣言的な方法でネストされたデータ構造を作成するためのドメイン固有言語 (DSL) を実装します。 resultBuilder 属性の使用方法の例については、「Result Builders」を参照してください。
Result-Building Methods
結果構築メソッド
A result builder implements static methoeds described below. Because all of the result builder’s functionality is exposed through static methods, you don’t ever initialize an instance of that type. A result builder must implement either the buildBlock(_:) method or both the buildPartialBlock(first:) and buildPartialBlock(accumulated:next:) methods. The other methods — which enable additional functionality in the DSL — are optional. The declaration of a result builder type doesn’t actually have to include any protocol conformance.
結果ビルダーは、以下で説明する静的メソッドを実装します。 結果ビルダーの機能はすべて静的メソッドを通じて公開されるため、その型のインスタンスを初期化する必要はありません。 結果ビルダーは、buildBlock(_:) メソッド、または buildPartialBlock(first:) メソッドと buildPartialBlock(accumulated:next:) メソッドの両方を実装する必要があります。 DSL の追加機能を有効にする他の方法はオプションです。 結果ビルダー型の宣言には、実際にはプロトコルへの準拠を含める必要はありません。
The description of the static methods uses three types as placeholders. The type Expression is a placeholder for the type of the result builder’s input, Component is a placeholder for the type of a partial result, and FinalResult is a placeholder for the type of the result that the result builder produces. You replace these types with the actual types that your result builder uses. If your result-building methods don’t specify a type for Expression or FinalResult, they default to being the same as Component.
静的メソッドの説明では、プレースホルダーとして 3 つの型を使用します。 型 Expression は結果ビルダーの入力の型のプレースホルダーであり、Component は部分的な結果の型のプレースホルダーであり、FinalResult は結果ビルダーが生成する結果の型のプレースホルダーです。 これらの型を、結果ビルダーが使用する実際の型に置き換えます。 結果構築メソッドで Expression または FinalResult の型を指定しない場合、デフォルトで Component と同じになります。
The block-building methods are as follows:
ブロックの構築方法は次のとおりです。
static func buildBlock(_ components: Component...) -> ComponentCombines an array of partial results into a single partial result.
部分的な結果の配列を 1 つの部分的な結果に結合します。
static func buildPartialBlock(first: Component) -> ComponentBuilds a partial result component from the first component. Implement both this method and buildPartialBlock(accumulated:next:) to support building blocks one component at a time. Compared to buildBlock(_:), this approach reduces the need for generic overloads that handle different numbers of arguments.
最初のコンポーネントから部分的な結果コンポーネントを構築します。 このメソッドと buildPartialBlock(accumulated:next:) の両方を実装して、一度に 1 つのコンポーネントのビルディング ブロックをサポートします。 buildBlock(_:) と比較して、このアプローチでは、さまざまな数の引数を処理する汎用オーバーロードの必要性が軽減されます。
static func buildPartialBlock(accumulated: Component, next: Component) -> ComponentBuilds a partial result component by combining an accumulated component with a new component. Implement both this method and buildPartialBlock(first:) to support building blocks one component at a time. Compared to buildBlock(_:), this approach reduces the need for generic overloads that handle different numbers of arguments.
蓄積されたコンポーネントと新しいコンポーネントを組み合わせて、部分的な結果コンポーネントを構築します。 このメソッドと buildPartialBlock(first:) の両方を実装して、一度に 1 つのコンポーネントのビルディング ブロックをサポートします。 buildBlock(_:) と比較して、このアプローチでは、さまざまな数の引数を処理する汎用オーバーロードの必要性が軽減されます。
A result builder can implement all three of the block-building methods listed above; in that case, availability determines which method is called. By default, Swift calls the buildPartialBlock(first:) and buildPartialBlock(accumulated:next:) methods. To make Swift call buildBlock(_:) instead, mark the enclosing declaration as being available before the availability you write on buildPartialBlock(first:) and buildPartialBlock(accumulated:next:).
結果ビルダーは、上記の 3 つのブロック構築メソッドをすべて実装できます。 その場合、可用性によってどのメソッドが呼び出されるかが決まります。 デフォルトでは、Swift は buildPartialBlock(first:) メソッドと buildPartialBlock(accumulated:next:) メソッドを呼び出します。 代わりに Swift で buildBlock(_:) を呼び出すようにするには、buildPartialBlock(first:) と buildPartialBlock(accumulated:next:) に書き込む可用性の前に、囲んでいる宣言を使用可能としてマークします。
The additional result-building methods are as follows:
追加の結果構築メソッドは次のとおりです。
static func buildOptional(_ component: Component?) -> ComponentBuilds a partial result from a partial result that can be nil. Implement this method to support if statements that don’t include an else clause.
nil の可能性がある部分的な結果から部分的な結果を構築します。 else 句を含まない if ステートメントをサポートするには、このメソッドを実装します。
static func buildEither(first: Component) -> ComponentBuilds a partial result whose value varies depending on some condition. Implement both this method and buildEither(second:) to support switch statements and if statements that include an else clause.
値が何らかの条件に応じて変化する部分的な結果を構築します。 switch ステートメントと else 句を含む if ステートメントをサポートするには、このメソッドと buildEither(second:) の両方を実装します。
static func buildEither(second: Component) -> ComponentBuilds a partial result whose value varies depending on some condition. Implement both this method and buildEither(first:) to support switch statements and if statements that include an else clause.
値が何らかの条件に応じて変化する部分的な結果を構築します。 このメソッドと buildEither(first:) の両方を実装して、switch ステートメントと else 句を含む if ステートメントをサポートします。
static func buildArray(_ components: [Component]) -> ComponentBuilds a partial result from an array of partial results. Implement this method to support for loops.
部分結果の配列から部分結果を構築します。 for ループをサポートするには、このメソッドを実装します。
static func buildExpression(_ expression: Expression) -> ComponentBuilds a partial result from an expression. You can implement this method to perform preprocessing — for example, converting expressions to an internal type — or to provide additional information for type inference at use sites.
式から部分的な結果を構築します。 このメソッドを実装すると、前処理 (式を内部型に変換するなど) を実行したり、使用サイトで型推論のための追加情報を提供したりできます。
static func buildFinalResult(_ component: Component) -> FinalResultBuilds a final result from a partial result. You can implement this method as part of a result builder that uses a different type for partial and final results, or to perform other postprocessing on a result before returning it.
部分的な結果から最終結果を構築します。 このメソッドは、部分結果と最終結果に異なる型を使用する結果ビルダーの一部として実装することも、結果を返す前に結果に対して他の後処理を実行することもできます。
static func buildLimitedAvailability(_ component: Component) -> ComponentBuilds a partial result that propagates or erases type information outside a compiler-control statement that performs an availability check. You can use this to erase type information that varies between the conditional branches.
可用性チェックを実行するコンパイラ制御ステートメントの外側で型情報を伝播または消去する部分的な結果を構築します。 これを使用して、条件分岐間で異なる型情報を消去できます。
For example, the code below defines a simple result builder that builds an array of integers. This code defines Component and Expression as type aliases, to make it easier to match the examples below to the list of methods above.
たとえば、以下のコードは、整数の配列を構築する単純な結果ビルダーを定義します。 このコードは、コンポーネントと式を型 エイリアスとして定義し、以下の例と上記のメソッドのリストを簡単に照合できるようにします。
@resultBuilder
struct ArrayBuilder {
typealias Component = [Int]
typealias Expression = Int
static func buildExpression(_ element: Expression) -> Component {
return [element]
}
static func buildOptional(_ component: Component?) -> Component {
guard let component = component else { return [] }
return component
}
static func buildEither(first component: Component) -> Component {
return component
}
static func buildEither(second component: Component) -> Component {
return component
}
static func buildArray(_ components: [Component]) -> Component {
return Array(components.joined())
}
static func buildBlock(_ components: Component...) -> Component {
return Array(components.joined())
}
}
Result Transformations
結果の変換
The following syntactic transformations are applied recursively to turn code that uses result-builder syntax into code that calls the static methods of the result builder type:
次の構文変換は再帰的に適用され、結果ビルダー構文を使用するコードを結果ビルダー型の静的メソッドを呼び出すコードに変換します。
・If the result builder has a buildExpression(_:) method, each expression becomes a call to that method. This transformation is always first. For example, the following declarations are equivalent:
・結果ビルダーに buildExpression(_:) メソッドがある場合、各式はそのメソッドの呼び出しになります。 この変換は常に最初に行われます。 たとえば、次の宣言は同等です。
@ArrayBuilder var builderNumber: [Int] { 10 }
var manualNumber = ArrayBuilder.buildExpression(10)・An assignment statement is transformed like an expression, but is understood to evaluate to (). You can define an overload of buildExpression(_:) that takes an argument of type () to handle assignments specifically.
・代入文は式のように変換されますが、() と評価されると理解されます。 割り当てを具体的に処理するために、型 () の引数を取る buildExpression(_:) のオーバーロードを定義できます。
・A branch statement that checks an availability condition becomes a call to the buildLimitedAvailability(_:) method. This transformation happens before the transformation into a call to buildEither(first:), buildEither(second:), or buildOptional(_:). You use the buildLimitedAvailability(_:) method to erase type information that changes depending on which branch is taken. For example, the buildEither(first:) and buildEither(second:) methods below use a generic type that captures type information about both branches.
・可用性条件をチェックする分岐ステートメントは、buildLimitedAvailability(:) メソッドの呼び出しになります。 この変換は、buildEither(first:)、buildEither(second:)、または buildOptional(:) への呼び出しへの変換の前に行われます。 buildLimitedAvailability(_:) メソッドを使用して、選択されたブランチに応じて変化する型情報を消去します。 たとえば、以下の buildEither(first:) メソッドと buildEither(second:) メソッドは、両方のブランチに関する型情報を取得するジェネリック型を使用します。
protocol Drawable {
func draw() -> String
}
struct Text: Drawable {
var content: String
init(_ content: String) { self.content = content }
func draw() -> String { return content }
}
struct Line<D: Drawable>: Drawable {
var elements: [D]
func draw() -> String {
return elements.map { $0.draw() }.joined(separator: "")
}
}
struct DrawEither<First: Drawable, Second: Drawable>: Drawable {
var content: Drawable
func draw() -> String { return content.draw() }
}
@resultBuilder
struct DrawingBuilder {
static func buildBlock<D: Drawable>(_ components: D...) -> Line<D> {
return Line(elements: components)
}
static func buildEither<First, Second>(first: First)
-> DrawEither<First, Second> {
return DrawEither(content: first)
}
static func buildEither<First, Second>(second: Second)
-> DrawEither<First, Second> {
return DrawEither(content: second)
}
}・However, this approach causes a problem in code that has availability checks:
・ただし、このアプローチでは、可用性チェックのあるコードで問題が発生します。
@available(macOS 99, *)
struct FutureText: Drawable {
var content: String
init(_ content: String) { self.content = content }
func draw() -> String { return content }
}
@DrawingBuilder var brokenDrawing: Drawable {
if #available(macOS 99, *) {
FutureText("Inside.future") // Problem
} else {
Text("Inside.present")
}
}
// The type of brokenDrawing is Line<DrawEither<Line<FutureText>, Line<Text>>>・In the code above, FutureText appears as part of the type of brokenDrawing because it’s one of the types in the DrawEither generic type. This could cause your program to crash if FutureText isn’t available at runtime, even in the case where that type is explicitly not being used.To solve this problem, implement a buildLimitedAvailability(_:) method to erase type information. For example, the code below builds an AnyDrawable value from its availability check.
・上記のコードでは、FutureText は DrawEither ジェネリック 型の型の 1 つであるため、brokenDrawing の型の一部として表示されます。 これにより、FutureText が実行時に利用できない場合、その型が明示的に使用されていない場合でも、プログラムがクラッシュする可能性があります。この問題を解決するには、buildLimitedAvailability(_:) メソッドを実装して型情報を消去します。 たとえば、以下のコードは、可用性チェックから AnyDrawable 値を構築します。
struct AnyDrawable: Drawable {
var content: Drawable
func draw() -> String { return content.draw() }
}
extension DrawingBuilder {
static func buildLimitedAvailability(_ content: Drawable) -> AnyDrawable {
return AnyDrawable(content: content)
}
}
@DrawingBuilder var typeErasedDrawing: Drawable {
if #available(macOS 99, *) {
FutureText("Inside.future")
} else {
Text("Inside.present")
}
}
// The type of typeErasedDrawing is Line<DrawEither<AnyDrawable, Line<Text>>>・A branch statement becomes a series of nested calls to the buildEither(first:) and buildEither(second:) methods. The statements’ conditions and cases are mapped onto the leaf nodes of a binary tree, and the statement becomes a nested call to the buildEither methods following the path to that leaf node from the root node.For example, if you write a switch statement that has three cases, the compiler uses a binary tree with three leaf nodes. Likewise, because the path from the root node to the second case is “second child” and then “first child”, that case becomes a nested call like buildEither(first: buildEither(second: ... )). The following declarations are equivalent:
・branch ステートメントは、buildEither(first:) メソッドと buildEither(second:) メソッドへの一連のネストされた呼び出しになります。 ステートメントの条件とケースはバイナリ ツリーのリーフ ノードにマッピングされ、ステートメントはルート ノードからそのリーフ ノードへのパスをたどる buildEither メソッドへのネストされた呼び出しになります。たとえば、次のような switch ステートメントを作成するとします。 には 3 つのケースがあり、コンパイラは 3 つのリーフ ノードを持つバイナリ ツリーを使用します。 同様に、ルートノードから 2 番目のケースへのパスは「2 番目の子」、次に「最初の子」であるため、そのケースは buildEither(first: buildEither(next: … )) のようなネストされた呼び出しになります。 次の宣言は同等です。
let someNumber = 19
@ArrayBuilder var builderConditional: [Int] {
if someNumber < 12 {
31
} else if someNumber == 19 {
32
} else {
33
}
}
var manualConditional: [Int]
if someNumber < 12 {
let partialResult = ArrayBuilder.buildExpression(31)
let outerPartialResult = ArrayBuilder.buildEither(first: partialResult)
manualConditional = ArrayBuilder.buildEither(first: outerPartialResult)
} else if someNumber == 19 {
let partialResult = ArrayBuilder.buildExpression(32)
let outerPartialResult = ArrayBuilder.buildEither(second: partialResult)
manualConditional = ArrayBuilder.buildEither(first: outerPartialResult)
} else {
let partialResult = ArrayBuilder.buildExpression(33)
manualConditional = ArrayBuilder.buildEither(second: partialResult)
}・A branch statement that might not produce a value, like an if statement without an else clause, becomes a call to buildOptional(_:). If the if statement’s condition is satisfied, its code block is transformed and passed as the argument; otherwise, buildOptional(_:) is called with nil as its argument. For example, the following declarations are equivalent:
・else句のないifステートメントなど、値を生成しない可能性のある分岐ステートメントは、buildOptional(:)の呼び出しになります。 if ステートメントの条件が満たされる場合、そのコード ブロックが変換され、引数として渡されます。 それ以外の場合は、buildOptional(:) が nil を引数として呼び出されます。 たとえば、次の宣言は同等です。
@ArrayBuilder var builderOptional: [Int] {
if (someNumber % 2) == 1 { 20 }
}
var partialResult: [Int]? = nil
if (someNumber % 2) == 1 {
partialResult = ArrayBuilder.buildExpression(20)
}
var manualOptional = ArrayBuilder.buildOptional(partialResult)・If the result builder implements the buildPartialBlock(first:) and buildPartialBlock(accumulated:next:) methods, a code block or do statement becomes a call to those methods. The first statement inside of the block is transformed to become an argument to the buildPartialBlock(first:) method, and the remaining statements become nested calls to the buildPartialBlock(accumulated:next:) method. For example, the following declarations are equivalent:
・結果ビルダーが buildPartialBlock(first:) メソッドと buildPartialBlock(accumulated:next:) メソッドを実装する場合、コード ブロックまたは do ステートメントはそれらのメソッドの呼び出しになります。 ブロック内の最初のステートメントは、buildPartialBlock(first:) メソッドの引数になるように変換され、残りのステートメントは buildPartialBlock(accumulated:next:) メソッドのネストされた呼び出しになります。 たとえば、次の宣言は同等です。
struct DrawBoth<First: Drawable, Second: Drawable>: Drawable {
var first: First
var second: Second
func draw() -> String { return first.draw() + second.draw() }
}
@resultBuilder
struct DrawingPartialBlockBuilder {
static func buildPartialBlock<D: Drawable>(first: D) -> D {
return first
}
static func buildPartialBlock<Accumulated: Drawable, Next: Drawable>(
accumulated: Accumulated, next: Next
) -> DrawBoth<Accumulated, Next> {
return DrawBoth(first: accumulated, second: next)
}
}
@DrawingPartialBlockBuilder var builderBlock: some Drawable {
Text("First")
Line(elements: [Text("Second"), Text("Third")])
Text("Last")
}
let partialResult1 = DrawingPartialBlockBuilder.buildPartialBlock(first: Text("first"))
let partialResult2 = DrawingPartialBlockBuilder.buildPartialBlock(
accumulated: partialResult1,
next: Line(elements: [Text("Second"), Text("Third")])
)
let manualResult = DrawingPartialBlockBuilder.buildPartialBlock(
accumulated: partialResult2,
next: Text("Last")
)・Otherwise, a code block or do statement becomes a call to the buildBlock(_:) method. Each of the statements inside of the block is transformed, one at a time, and they become the arguments to the buildBlock(_:) method. For example, the following declarations are equivalent:
・それ以外の場合、コードブロックまたは do ステートメントは buildBlock(:) メソッドの呼び出しになります。 ブロック内の各ステートメントは一度に 1 つずつ変換され、buildBlock(:) メソッドの引数になります。 たとえば、次の宣言は同等です。
@ArrayBuilder var builderBlock: [Int] {
100
200
300
}
var manualBlock = ArrayBuilder.buildBlock(
ArrayBuilder.buildExpression(100),
ArrayBuilder.buildExpression(200),
ArrayBuilder.buildExpression(300)
)・A for loop becomes a temporary variable, a for loop, and call to the buildArray(_:) method. The new for loop iterates over the sequence and appends each partial result to that array. The temporary array is passed as the argument in the buildArray(_:) call. For example, the following declarations are equivalent:
・for ループは一時変数、for ループになり、buildArray(:) メソッドを呼び出します。 新しい for ループはシーケンスを反復処理し、各部分的な結果をその配列に追加します。 一時配列は、buildArray(:) 呼び出しの引数として渡されます。 たとえば、次の宣言は同等です。
@ArrayBuilder var builderArray: [Int] {
for i in 5...7 {
100 + i
}
}
var temporary: [[Int]] = []
for i in 5...7 {
let partialResult = ArrayBuilder.buildExpression(100 + i)
temporary.append(partialResult)
}
let manualArray = ArrayBuilder.buildArray(temporary)・If the result builder has a buildFinalResult(_:) method, the final result becomes a call to that method. This transformation is always last.
・結果ビルダーに buildFinalResult(_:) メソッドがある場合、最終結果はそのメソッドの呼び出しになります。 この変換は常に最後に行われます。
Although the transformation behavior is described in terms of temporary variables, using a result builder doesn’t actually create any new declarations that are visible from the rest of your code.
変換動作は一時変数の観点から説明されていますが、結果ビルダーを使用しても、コードの残りの部分から見える新しい宣言は実際には作成されません。
You can’t use break, continue, defer, guard, or return statements, while statements, or do–catch statements in the code that a result builder transforms.
結果ビルダーが変換するコード内では、break、 continue、defer、guard、return ステートメント、while ステートメント、do-catch ステートメントを使用できません。
The transformation process doesn’t change declarations in the code, which lets you use temporary constants and variables to build up expressions piece by piece. It also doesn’t change throw statements, compile-time diagnostic statements, or closures that contain a return statement.
変換プロセスではコード内の宣言は変更されないため、一時的な定数や変数を使用して式を少しずつ構築できます。 また、throw ステートメント、コンパイル時の診断ステートメント、return ステートメントを含むクロージャも変更されません。
Whenever possible, transformations are coalesced. For example, the expression 4 + 5 * 6 becomes buildExpression(4 + 5 * 6) rather multiple calls to that function. Likewise, nested branch statements become a single binary tree of calls to the buildEither methods.
可能な限り、変換は合体します。 たとえば、式 4 + 5 * 6 は、その関数を複数回呼び出すのではなく、buildExpression(4 + 5 * 6) になります。 同様に、ネストされたブランチ ステートメントは、buildEither メソッドを呼び出す単一のバイナリ ツリーになります。
Custom Result-Builder Attributes
カスタム結果ビルダー属性
Creating a result builder type creates a custom attribute with the same name. You can apply that attribute in the following places:
結果ビルダー 型を作成すると、同じ名前のカスタム属性が作成されます。 この属性は次の場所に適用できます。
- On a function declaration, the result builder builds the body of the function.
- 関数宣言では、結果ビルダーが関数の本体を構築します。
- On a variable or subscript declaration that includes a getter, the result builder builds the body of the getter.
- ゲッターを含む変数または添字宣言では、結果ビルダーはゲッターの本体を構築します。
- On a parameter in a function declaration, the result builder builds the body of a closure that’s passed as the corresponding argument.
- 関数宣言内のパラメーターで、結果ビルダーは、対応する引数として渡されるクロージャーの本体を構築します。
Applying a result builder attribute doesn’t impact ABI compatibility. Applying a result builder attribute to a parameter makes that attribute part of the function’s interface, which can affect source compatibility.
結果ビルダー属性を適用しても、ABI の互換性には影響しません。 結果ビルダー属性をパラメーターに適用すると、その属性が関数のインターフェイスの一部となり、ソースの互換性に影響を与える可能性があります。
requires_stored_property_inits
保存プロパティの初期化要求
Apply this attribute to a class declaration to require all stored properties within the class to provide default values as part of their definitions. This attribute is inferred for any class that inherits from NSManagedObject.
この属性をクラス宣言に適用すると、クラス内のすべての格納プロパティに定義の一部としてデフォルト値を提供することが要求されます。 この属性は、NSManagedObject を継承するクラスに対して推論されます。
testable
テスト可能
Apply this attribute to an import declaration to import that module with changes to its access control that simplify testing the module’s code. Entities in the imported module that are marked with the internal access-level modifier are imported as if they were declared with the public access-level modifier. Classes and class members that are marked with the internal or public access-level modifier are imported as if they were declared with the open access-level modifier. The imported module must be compiled with testing enabled.
この属性をimport宣言に適用して、モジュールのコードのテストを簡素化するアクセス制御の変更を含むモジュールをインポートします。 インポートされたモジュール内のinternalアクセスレベル修飾子でマークされたエンティティは、public アクセスレベル修飾子で宣言されているかのようにインポートされます。 internalアクセスレベル修飾子またはpublicアクセスレベル修飾子でマークされたクラスとクラスメンバーは、openアクセスレベル修飾子で宣言されているかのようにインポートされます。 インポートされたモジュールは、テストを有効にしてコンパイルする必要があります。
UIApplicationMain
UIアプリケーションメイン
Deprecated
廃止
This attribute is deprecated; use the main attribute instead. In Swift 6, using this attribute will be an error.
この属性は非推奨です。 代わりに main 属性を使用してください。 Swift 6 では、この属性を使用するとエラーになります。
Apply this attribute to a class to indicate that it’s the application delegate. Using this attribute is equivalent to calling the UIApplicationMain function and passing this class’s name as the name of the delegate class.
この属性をクラスに適用して、それがアプリケーション デリゲートであることを示します。 この属性を使用することは、UIApplicationMain 関数を呼び出して、このクラスの名前をデリゲート クラスの名前として渡すことと同じです。
If you don’t use this attribute, supply a main.swift file with code at the top level that calls the UIApplicationMain(_:_:_:_:)(Link:developer.apple.com) function. For example, if your app uses a custom subclass of UIApplication as its principal class, call the UIApplicationMain(_:_:_:_:) function instead of using this attribute.
この属性を使用しない場合は、UIApplicationMain(::::) (Link:developer.apple.com)(英語)関数を呼び出す最上位のコードを含む main.swift ファイルを指定します。 たとえば、アプリが UIApplication のカスタム サブクラスをプリンシパル クラスとして使用している場合は、この属性を使用する代わりに UIApplicationMain(::::) 関数を呼び出します。
The Swift code you compile to make an executable can contain at most one top-level entry point, as discussed in Top-Level Code.
「トップレベルのコード」で説明したように、実行可能ファイルを作成するためにコンパイルする Swift コードには、トップレベルのエントリ ポイントを 1 つだけ含めることができます。
unchecked
チェックされていない
Apply this attribute to a protocol type as part of a type declaration’s list of adopted protocols to turn off enforcement of that protocol’s requirements.
この属性を、型宣言の採用プロトコルのリストの一部としてプロトコル型に適用して、そのプロトコルの要件の強制をオフにします。
The only supported protocol is Sendable(Link:developer.apple.com).
サポートされているプロトコルはSendable(Link:developer.apple.com)(英語)のみです。
usableFromInline
インラインから使用可能
Apply this attribute to a function, method, computed property, subscript, initializer, or deinitializer declaration to allow that symbol to be used in inlinable code that’s defined in the same module as the declaration. The declaration must have the internal access-level modifier. A structure or class marked usableFromInline can use only types that are public or usableFromInline for its properties. An enumeration marked usableFromInline can use only types that are public or usableFromInline for the raw values and associated values of its cases.
この属性を関数、メソッド、計算プロパティ、添字、初期化子、または初期化解除子の宣言に適用すると、宣言と同じモジュールで定義されているインライン可能コードでそのシンボルを使用できるようになります。 宣言にはinternalアクセスレベル修飾子が必要です。 useableFromInline とマークされた構造体またはクラスは、そのプロパティに public または useableFromInline の型のみを使用できます。 useableFromInline とマークされた列挙は、そのケースの生の値と関連する値に public または useableFromInline の型のみを使用できます。
Like the public access-level modifier, this attribute exposes the declaration as part of the module’s public interface. Unlike public, the compiler doesn’t allow declarations marked with usableFromInline to be referenced by name in code outside the module, even though the declaration’s symbol is exported. However, code outside the module might still be able to interact with the declaration’s symbol by using runtime behavior.
public アクセスレベル修飾子と同様に、この属性はモジュールのパブリック インターフェースの一部として宣言を公開します。 public とは異なり、コンパイラは、宣言のシンボルがエクスポートされている場合でも、usableFromInline でマークされた宣言をモジュール外のコードで名前で参照することを許可しません。 ただし、モジュールの外部のコードは、実行時の動作を使用して宣言のシンボルと対話できる可能性があります。
Declarations marked with the inlinable attribute are implicitly usable from inlinable code. Although either inlinable or usableFromInline can be applied to internal declarations, applying both attributes is an error.
inlinable 属性でマークされた宣言は、インライン可能コードから暗黙的に使用できます。 inlinable または useableFromInline のいずれかをinternal宣言に適用できますが、両方の属性を適用するとエラーになります。
warn_unqualified_access
不正なアクセスを警告する
Apply this attribute to a top-level function, instance method, or class or static method to trigger warnings when that function or method is used without a preceding qualifier, such as a module name, type name, or instance variable or constant. Use this attribute to help discourage ambiguity between functions with the same name that are accessible from the same scope.
この属性をトップレベル関数、インスタンス メソッド、またはクラスまたは静的メソッドに適用すると、その関数またはメソッドがモジュール名、型名、インスタンス変数や定数などの前に修飾子なしで使用されたときに警告がトリガーされます。 この属性を使用すると、同じスコープからアクセスできる同じ名前の関数間のあいまいさを防ぐことができます。
For example, the Swift standard library includes both a top-level min(_:_:)(Link:developer.apple.com) function and a min()(Link:developer.apple.com) method for sequences with comparable elements. The sequence method is declared with the warn_unqualified_access attribute to help reduce confusion when attempting to use one or the other from within a Sequence extension.
たとえば、Swift 標準ライブラリには、最上位の min(_:_:)(Link:developer.apple.com)(英語) 関数と、同等の要素を持つシーケンス用の min() (Link:developer.apple.com)(英語)メソッドの両方が含まれています。 シーケンス拡張機能内でどちらかを使用しようとするときの混乱を軽減するために、Sequence メソッドは warn_unqualified_access 属性を使用して宣言されます。
Declaration Attributes Used by Interface Builder
Interface Builder で使用される宣言属性
Interface Builder attributes are declaration attributes used by Interface Builder to synchronize with Xcode. Swift provides the following Interface Builder attributes: IBAction, IBSegueAction, IBOutlet, IBDesignable, and IBInspectable. These attributes are conceptually the same as their Objective-C counterparts.
Interface Builder 属性は、Xcode と同期するために Interface Builder によって使用される宣言属性です。 Swift は、IBAction、IBSegueAction、IBOutlet、IBDesignable、および IBInspectable の Interface Builder 属性を提供します。 これらの属性は、概念的には Objective-C の対応する属性と同じです。
You apply the IBOutlet and IBInspectable attributes to property declarations of a class. You apply the IBAction and IBSegueAction attribute to method declarations of a class and the IBDesignable attribute to class declarations.
IBOutlet 属性と IBInspectable 属性をクラスのプロパティ宣言に適用します。 IBAction 属性と IBSegueAction 属性をクラスのメソッド宣言に適用し、IBDesignable 属性をクラス宣言に適用します。
Applying the IBAction, IBSegueAction, IBOutlet, IBDesignable, or IBInspectable attribute also implies the objc attribute.
IBAction、IBSegueAction、IBOutlet、IBDesignable、または IBInspectable 属性を適用すると、objc 属性も暗黙的に適用されます。
Type Attributes
型属性
You can apply type attributes to types only.
型属性は型にのみ適用できます。
autoclosure
自動閉鎖
Apply this attribute to delay the evaluation of an expression by automatically wrapping that expression in a closure with no arguments. You apply it to a parameter’s type in a function or method declaration, for a parameter whose type is a function type that takes no arguments and that returns a value of the type of the expression. For an example of how to use the autoclosure attribute, see Autoclosures and Function Type.
この属性を適用すると、引数のないクロージャで式を自動的にラップすることにより、式の評価を遅らせます。 これは、関数またはメソッド宣言内のパラメーターの型に適用します。そのパラメーターの型が、引数をとらず、式の型の値を返す関数型である場合です。autoclosure属性の使用方法の例については、オートクロージャと関数型をご覧ください。
convention
規則
Apply this attribute to the type of a function to indicate its calling conventions.
この属性を関数の型に適用して、関数の呼び出し規則を示します。
The convention attribute always appears with one of the following arguments:
convention属性は常に次のいずれかの引数とともに表示されます。
- The
swiftargument indicates a Swift function reference. This is the standard calling convention for function values in Swift. swift引数は、Swift 関数の参照を示します。 これは、Swift の関数値の標準呼び出し規則です。- The
blockargument indicates an Objective-C compatible block reference. The function value is represented as a reference to the block object, which is anid-compatible Objective-C object that embeds its invocation function within the object. The invocation function uses the C calling convention. block引数は、Objective-C 互換のブロック参照を示します。 関数の値は、ブロック オブジェクトへの参照として表されます。ブロック オブジェクトは、オブジェクト内に呼び出し関数が埋め込まれたid互換の Objective-C オブジェクトです。 呼び出し関数は C 呼び出し規約を使用します。- The
cargument indicates a C function reference. The function value carries no context and uses the C calling convention. c引数は C 関数参照を示します。 関数値にはコンテキストが含まれず、C 呼び出し規則が使用されます。
With a few exceptions, a function of any calling convention can be used when a function any other calling convention is needed. A nongeneric global function, a local function that doesn’t capture any local variables, or a closure that doesn’t capture any local variables can be converted to the C calling convention. Other Swift functions can’t be converted to the C calling convention. A function with the Objective-C block calling convention can’t be converted to the C calling convention.
いくつかの例外を除き、他の呼び出し規約の関数が必要な場合は、任意の呼び出し規約の関数を使用できます。 非ジェネリックなグローバル関数、ローカル変数をキャプチャしないローカル関数、またはローカル変数をキャプチャしないクロージャは、C 呼び出し規約に変換できます。 他の Swift 関数は C 呼び出し規約に変換できません。 Objective-C のブロック呼び出し規則を持つ関数は、C の呼び出し規則に変換できません。
escaping
エスケーピング
Apply this attribute to a parameter’s type in a function or method declaration to indicate that the parameter’s value can be stored for later execution. This means that the value is allowed to outlive the lifetime of the call. Function type parameters with the escaping type attribute require explicit use of self. for properties or methods. For an example of how to use the escaping attribute, see Escaping Closures.
この属性を関数またはメソッド宣言のパラメーターの型に適用して、後で実行するためにパラメーターの値を保存できることを示します。 これは、値が呼び出しの存続期間を超えて存続できることを意味します。 escaping型属性を持つ関数型パラメータでは、self を明示的に使用する必要があります。 プロパティまたはメソッドの場合。 escaping属性の使用方法の例については、「クロージャのエスケープ」を参照してください。
Sendable
送信可能
Apply this attribute to the type of a function to indicate that the function or closure is sendable. Applying this attribute to a function type has the same meaning as conforming a non–function type to the Sendable(Link:developer.apple.com) protocol.
この属性を関数の型に適用して、関数またはクロージャが送信可能であることを示します。 この属性を関数タイプに適用することは、関数以外のタイプを Sendable(Link:developer.apple.com)(英語) プロトコルに準拠させることと同じ意味を持ちます。
This attribute is inferred on functions and closures if the function or closure is used in a context that expects a sendable value, and the function or closure satisfies the requirements to be sendable.
この属性は、関数またはクロージャが送信可能な値を予期するコンテキストで使用され、関数またはクロージャが送信可能であるための要件を満たしている場合に、関数およびクロージャで推論されます。
A sendable function type is a subtype of the corresponding nonsendable function type.
送信可能な関数型は、対応する送信不可能な関数型のサブタイプです。
Switch Case Attributes
スイッチケースの属性
You can apply switch case attributes to switch cases only.
switch case 属性は、switch case にのみ適用できます。
unknown
未知
Apply this attribute to a switch case to indicate that it isn’t expected to be matched by any case of the enumeration that’s known at the time the code is compiled. For an example of how to use the unknown attribute, see Switching Over Future Enumeration Cases.
この属性を switch case に適用して、コードのコンパイル時にわかっている列挙型のどの case とも一致することが期待されていないことを示します。 unknownの使用方法の例については、「将来の列挙ケースの切り替え」を参照してください。
Grammar of an attribute
attribute → @ attribute-name attribute-argument-clause?
attribute-name → identifier
attribute-argument-clause → ( balanced-tokens? )
attributes → attribute attributes?
balanced-tokens → balanced-token balanced-tokens?
balanced-token → ( balanced-tokens? )
balanced-token → [ balanced-tokens? ]
balanced-token → { balanced-tokens? }
balanced-token → Any identifier, keyword, literal, or operator
balanced-token → Any punctuation except (, ), [, ], {, or }
