Previous << Interfaces
Next >> Intersection Types
列挙型(Enumerations)とは、一意の定数値に結び付けられたシンボル名(symbolic names)の集合であり、同一性(identity)によって比較できるものです。
Enum Declaration
列挙型(Enum)は、enum
キーワードを使用して宣言します。その後、列挙型の名前、コロン(:)の後にraw 型、そして開始と終了の波括弧で囲む必要があります。
raw 型は整数型サブタイプでなければならず、例えば、UInt8
または Int128
などです。
列挙型ケース(enum case)は、case
キーワードを使用して宣言し、その後に列挙型ケースの名前を続けます。
列挙型ケース(enum case)は一意でなければなりません。各列挙型caseには、すべてのcaseの中でのcaseのインデックスであるraw 値があります。
列挙型ケース(enum case)のraw 値は、rawValue
フィールドを使用してアクセスできます。
列挙型ケース(enum case)は、列挙型のフィールドとして名前を使用するか、引数としてraw 値を指定する必要がある列挙型コンストラクタを使用してアクセスできます。列挙型コンストラクタは、指定された生の値を持つ列挙型のcaseを返します。そのようなcaseが存在しない場合は、nil
を返します。
列挙型のcaseは、等価演算子==
および!=
を使用して比較できます。
/* Declare an enum named `Color` which has the raw value type `UInt8`,
* and declare three enum cases: `red`, `green`, and `blue`
*/
access(all)
enum Color: UInt8 {
access(all)
case red
access(all)
case green
access(all)
case blue
}
/* Declare a variable which has the enum type `Color` and initialize
it to the enum case `blue` of the enum */
let blue: Color = Color.blue
/* Get the raw value of the enum case `blue`.
* As it is the third case, so it has index 2
*/
blue.rawValue /* is `2` */
/* Get the `green` enum case of the enum `Color` by using the enum
* constructor and providing the raw value of the enum case `green`, 1,
* as the enum case `green` is the second case, so it has index 1
*/
let green: Color? = Color(rawValue: 1)
/* is `Color.green` */
/* Get the enum case of the enum `Color` that has the raw value 5.
* As there are only three cases, the maximum raw value / index is 2.
*/
let nothing = Color(rawValue: 5)
/* is `nil` */
/* Enum cases can be compared */
Color.red == Color.red /* is `true` */
Color(rawValue: 1) == Color.green
/* is `true` */
/* Different enum cases are not the same */
Color.red != Color.blue /* is `true` */
翻訳元
Flow BlockchainのCadence version1.0ドキュメント (Enumerations)