# 基本运算符

## 1. 赋值运算符

与 C 语言和 Objective-C 不同，**Swift 的赋值操作并不返回任何值**。所以下面语句是无效的：

```swift

if x = y { // 此句错误，因为 x = y 并不返回任何值
    
}

let b = a += 2  // 赋值运算符没有返回值， a += 2  不会有返回值

```

## 2. 算术运算符

与 C 语言和 Objective-C 不同的是，**Swift 默认情况下不允许在数值运算中出现溢出情况**。

```swift

let a : Int = Int.max + 1 ;   // 出现溢出

```

加法运算符也可用于 String 的拼接：

```swift
"hello, " + "world"  // 等于 "hello, world"
```

### 3. 比较运算符

Swift 提供恒等（===）和不恒等（!==）这两个比较符来判断两个对象是否引用同一个对象实例。

Swift支持对元组的比较, 当然每个元素都要支持比较运算符，对每个元素按照字典顺序比较

```swift

(1, "zebra") < (2, "apple")   // true，因为 1 小于 2
(3, "apple") < (3, "bird")    // true，因为 3 等于 3，但是 apple 小于 bird
(4, "dog") == (4, "dog")      // true，因为 4 等于 4，dog 等于 dog

("blue", false) < ("purple", true) // 错误，因为 < 不能比较布尔类型

```

> Swift 标准库只能比较七个以内元素的元组比较函数。如果你的元组元素超过七个时，你需要自己实现比较运算符。

## 4. 空合运算符

空合运算符（a ?? b）将对可选类型 a 进行空判断，如果 a 包含一个值就进行解包，否则就返回一个默认值 b。表达式 a 必须是 Optional 类型。默认值 b 的类型必须要和 a 存储值的类型保持一致。

```swift

let defaultColorName = "red"
var userDefinedColorName: String?   //默认值为 nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName 的值为空，所以 colorNameToUse 的值为 "red"

```

## 5. 区间运算符

Swift 提供了几种方便表达一个区间的值的区间运算符。

### 5.1

**闭区间运算符a...b**定义一个包含从 a 到 b（包括 a 和 b）的所有值的区间。a 的值不能超过 b。

```swift
for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}
// 1 * 5 = 5
// 2 * 5 = 10
// 3 * 5 = 15
// 4 * 5 = 20
// 5 * 5 = 25
```

### 5.2 半开区间运算符

**半开区间运算符a..\<b**定义一个从 a 到 b 但不包括 b 的区间。

半开区间的实用性在于当你使用一个从 0 开始的列表（如数组）时，非常方便地从0数到列表的长度。

### 5.3 单侧区间

闭区间操作符有另一个表达形式，可以表达往一侧无限延伸的区间

可以在数组下标中使用

```swift

for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian
```

单侧区间不止可以在下标里使用，也可以在别的情境下使用。然而，由于这种区间无限延伸的特性，请保证你在循环里有一个结束循环的分支


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/swift/2.-ji-ben-yun-suan-fu/1.-ji-ben-yun-suan-fu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
