# その他の文法 (Castなど)

### 乱数生成

```swift
access(all) fun rollDice(): UInt64 {
    // modulo: 6 returns 0, 1, 2, 3, 4, or 5
    let rawRoll: UInt64 = revertibleRandom(modulo: 6)
    return rawRoll + 1
}
```

* * *

### 現在時刻の取得

```swift
self.execTime = getCurrentBlock().timestamp // 秒単位まで
```

乱数生成と現在時刻取得はグローバルメソッドでありimportは何も必要ありません。

* * *

## 型変換

### **Cast**

```swift
let integer: Int = 1
// This is an upcast.
let number = integer as Number // number = 1 and has type Number.  (as はDowncastには使えません)
```

### **Conditional Downcast**

```swift
let something: AnyStruct = 1
let number: Int? = something as? Int    // 1
let boolean: Bool? = something as? Bool // nil (as?はDowncastに使えます。subtypeでなくCast出来ない場合はnilを返す)
```

### **Forced Downcast**

```swift
let something: AnyStruct = 1
let number: Int? = something as! Int  // 1 (as! はDowncastに使えます。 subtypeでない場合はnilを返す)
```

### **Forced Unwrap (**`!`**)**

```swift
let c: Int? = 3
let d: Int = c!
```

* * *

## Resource Interface

インターフェイスは、実装しなければならない動作（関数やフィールド）の規約を定義するものです。

```swift
access(all) resource interface IGreeting {
    access(all) let greeting: String
}

access(all) resource Greeting: IGreeting {
    access(all) let greeting: String
    init() {
        self.greeting = "Hello, World!"
    }
}

access(all) fun createRestrictedGreeting(): @{IGreeting} {
    return <- create Greeting()
}
```

*   インターフェイス型として扱う場合は、`@{IGreeting}` のように指定します。
    
*   メソッドやフィールドへの詳細なアクセス制限を行いたい場合は、Entitlement を使用して制御します。
    

(若干、Cadence v1.0以前とCadence v1.0では変更が発生しています。 `@Greeting{IGreeting}` 構文は廃止され、`@{IGreeting}` のように指定するなど。)

* * *

## Operator

`=`

```swift
var a = 4
```

`<-`

```swift
// リソースを空の変数またはコンテナに移動します。
// 空でないと判断できる場合コンパイルエラーとなります。代わりに<-!を使用してください
return <- create Arms(attack: attack)
```

`<-!`

```swift
// リソースを Optional (@T?) に代入します。その際、現在の値が nil であることを前提とします（nil でない場合はパニックします）。
self.equippedWeapon <-! newWeapon
```

`<->`

```swift
// どちらもdestroyすることなく、2つのリソースをアトミックに入れ替えます。
var mainHand: @Arms <- create Arms(name: "Excalibur")
var storage: @Arms? <- nil
mainHand <-> storage
```

arithmetic(`+, -, *, /, %`)

```swift
let a = 1 + 2 // is 3
```

super-types (Upcast & Downcast)

```swift
// 抽象型 Integer へのアップキャストと、演算実行のための具象型 Int8 へのダウンキャスト（as!）
let x: Integer = 3 as Int8
let y: Integer = 4 as Int8 
let z: Integer = (x as! Int8) + (y as! Int8)
// 1. Storing an Int8 in an Integer variable is an upcast.
// 2. Similarly, 4 is created as Int8 and upcast to Integer.
// 3. Integer is an abstract super-type / interface which does not allow direct arithmetic. Therefore, x and y must be explicitly downcast back to their concrete type using as!.
```

Ternary Conditional

```swift
let x: Int = 1 > 2 ? 3 : 4     // 4
let y: Int? = 1 > 2 ? nil : 3  // 3
```

Nil-Coalescing (`??`)

```swift
let a: Int? = nil
let b: Int = a ?? 42 // Optional型がnilでなければその値を返し、nilであれば代替の値を返す。)
```

`!`

```swift
let a = true
let b = !a // false
```

`&&`

```swift
true && true    // true
true && false   // false
```

`||`

```swift
false || true   // true
false || false  // false
```

`==`

```swift
let x: Int? = 1
x == nil  // false

// Comparisons of different levels of optionals are possible.
let x: Int? = 2
let y: Int?? = 2
x == y    // true

let a: Int? = nil            // nil
let b: Int?? = nil           // nil (outer level is nil)
let c: Int?? = (nil as Int?) // Some(nil) (inner level is nil)

a == b // true
b == c // false (b is nil, but c contains an optional holding nil!)
```

`!=`

```swift
let x: Int? = 1
x != nil  // true

// Comparisons of different levels of optionals are possible.
let x: Int? = 2
let y: Int?? = 2
x != y    // false
```

`<`

```swift
 1 < 2  // true
 2 < 1  // false
```

`<=`

```swift
 1 <= 1  // true
 2 <= 1  // false
```

`>`

```swift
 1 > 1  // false
 2 > 1  // true
```

`>=`

```swift
 1 >= 1  // true
 1 >= 2  // false
```

* * *

### **Bitwise operator**

Bitwise AND (`&`)

```swift
let firstFiveBits = 0b11111000
let lastFiveBits  = 0b00011111
let middleTwoBits = firstFiveBits & lastFiveBits  // 0b00011000
```

Bitwise OR (`|`)

```swift
let someBits = 0b10110010
let moreBits = 0b01011110
let combinedbits = someBits | moreBits  // 0b11111110
```

Bitwise XOR (`^`)

```swift
let firstBits = 0b00010100
let otherBits = 0b00000101
let outputBits = firstBits ^ otherBits  // 0b00010001
```

Bitwise LEFT SHIFT (`<<`)

```swift
let someBits = 4  // 0b00000100
let shiftedBits = someBits << 2   // 0b00010000
```

Bitwise RIGHT SHIFT (`>>`)

```swift
let someBits = 8  // 0b00001000
let shiftedBits = someBits >> 2   // 0b00000010
```

* * *
