> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift-playgrounds/learn-to-code-2/pages/variables/checking-for-equal-values.md).

# 檢查相等值

Checking for Equal Values

這個關卡會自動以亂數決定開關的數量 (`numberOfSwitches`)，然後我們要寫程式讓圖中的角色收集「同樣數量」的寶石。

![](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5-JmwCZMKh_d7RfBaN%2F-M5RX8jDTcj-vcsChEPZ%2F-M5Rb0HAdxhgcqjB2YWT%2Fcheck%20for%20equal%20values.PNG?alt=media\&token=31750506-002d-49d2-aca2-6f68a60744d9)

{% tabs %}
{% tab title="main" %}

```swift
// 變數初始設定
let switchCounter = numberOfSwitches
var gems = 0

// 如果寶石比開關數少就繼續走
while gems < switchCounter {
    walkAlongLeft {
        if isOnGem { 
            collectGem() 
            gems += 1
        }
    }
}
```

{% endtab %}

{% tab title="navigation (right)" %}

```swift
// ⭐️ 貼著右邊走的策略，
//    將來可以寫入 Actor 的 extension 中。
func walkAlongRight(handle:()->Void) {

    // 如果右邊沒擋住，就向右轉、走一步，然後做該做的事
    if !isBlockedRight {
        turnRight()
        moveForward()
        handle()
    } 
    
    // 不然如果前面沒擋住，就向前走一步，然後做該做的事
    else if !isBlocked {
        moveForward()
        handle()
    } 
    
    // 不然就向左轉
    else {
        turnLeft()
    }
}

```

{% endtab %}

{% tab title="navigation (left)" %}

```swift
func walkAlongLeft(handle:()->Void) {
    
    if !isBlockedLeft {    // 如果左邊沒擋住，就向左轉走一步，然後做該做的事
        turnLeft()
        moveForward()
        handle()
    } else if !isBlocked { // 不然如果前面沒擋住，就向前走一步，然後做該做的事
        moveForward()
        handle()
    } else {               // 不然就向左轉
        turnRight()
    }
}
```

{% endtab %}
{% endtabs %}

參考影片

{% embed url="<https://youtu.be/fGu4NVvYYho>" %}
