> For the complete documentation index, see [llms.txt](https://pakornpat.gitbook.io/ios-app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pakornpat.gitbook.io/ios-app/swift/operator.md).

# Operator

### Math Operators

Math operators ก็จะเหมือนในภาษาอื่น ๆ เช่น `+` `-` `*` `/` `%` เช่น

```swift
var x = 5
x = x + 1
x = 5 - x
```

`+` เรายังสามารถใช้ concat ทั้ง `String` และ `Array` ได้ด้วย

```swift
let names = ["Pop"] + ["John"]
```

{% hint style="info" %}
ในการหารเอาเศษเรามักจะใช้ `%` เช่น

```swift
let remainder = 17 % 5
// remainder = 2
```

แต่ใน swift เราสามารถเขียนให้อ่านเป็นประโยคได้แบบนี้

```swift
17.remainder(dividingBy: 5)
```

{% endhint %}

{% hint style="info" %}
ในภาษาอื่น ๆ จะมี operator `++` เพื่อใช้ increment ค่าทีละ `1` เช่น

```swift
x = 0
x++    // Unary operator '++' cannot be applied
```

เนื่องจากถ้าใช้งานได้ มักจะทำให้เกิดความกำกวม เช่น `x = x+++++x` ทำให้ภาษา Swift ตัด operator นี้ทิ้งไป จึงทำให้เขียนได้แค่แบบนี้

```swift
x = x + 1
x += 1
```

{% endhint %}

### Logical Operators

นอกจาก Operators ทางคณิตศาสตร์ Swift ก็ยังมี Operators ทางตรรกศาสตร์แบบภาษาอื่น ๆ เช่น

* `&&` แทน และ
* `||` แทน หรือ
* `!` แทน นิเสธ

มี Operators ในการเปรียบเทียบ

* `==` เปรียบเทียบค่าเท่ากัน
* `!=` เปรียบเทียบค่าไม่เท่ากัน
* `>` เปรียบเทียบค่าซ้ายมากกว่า
* `>=` เปรียบเทียบค่าซ้ายมากกว่าหรือเท่ากับ
* `<` เปรียบเทียบค่าซ้ายน้อยกว่า
* `<=` ในการ เปรียบเทียบค่าซ้ายน้อยกว่าหรือเท่ากับ

{% hint style="info" %}
ในการเปรียบเทียบว่า เป็น `object instance` เดียวกันหรือไม่จะใช้ `===` หรือ `!==` เช่น

```swift
if obj1 === obj2 {
  // do something 
}
```

{% endhint %}

### Range Operators

Swift ยังมี Range Operators ให้ใช้งานด้วย เช่น

* Close range operator `...` เช่น `numbers`  range ตั้งแต่ `0` ถึง `5`

  ```swift
  let numbers = 0...5
  ```
* Half-open range operator `..<` เช่น `numbers` range ตั้งแต่ `0` ถึง`4`

  ```swift
  let numbers = 0..<5
  ```
* One-side range operator มักใช้ใน index ของ Array เช่น

  ```swift
  let a = [-1,-2,-3,0,1,2,3]
  let b = a[2...]      // b = [-3,0,1,2,3]
  let c = a[...2]      // c = [-1,-2,-3]
  let e = a[..<2]      // d = [-1,-2]
  ```
