---
title: "[译]Swift中的空字符串"
description: "Swift 一个特色就是有很多的语法糖，初学可能觉得hold不住，实际用的时候倒是挺便利。这里很多空字符串方法。"
url: "https://hicc.pro/p/blog/empty-strings-in-swift"
author: "tyler wang"
published: "2019-06-01T16:56:37.000Z"
updated: "2021-07-03T09:20:25.000Z"
category: "blog"
tags:
  - "Swift"
  - "翻译"
image: "https://image.hicc.pro/pro/20210703171945Foo-a7EIhDbxD5a89-MUPki_8Oq-mY5g0CufomTUYOEZJvpoh.jpg"
lang: "zh-CN"
site: "Hipo日志"
---

# [译]Swift中的空字符串

## 

Swift 一个特色就是有很多的语法糖，初学可能觉得hold不住，实际用的时候倒是挺便利。

基于对此的喜爱，简单转译一篇短文，[Empty Strings in Swift](https://useyourloaf.com/blog/empty-strings-in-swift/)。

---

### `isEmpty`属性

Swift中`String`是字符的结合，遵循`Collection`协议。因此会有`isEmpty`的属性，来判断字符串是否为空。

```swift
var isEmpty: Bool {get}
```

`Collection.swift`的具体实现是：

```swift
public var isEmpty: Bool {
	return startIndex == endIndex
}
```

```swift
"Hello".isEmpty  // false
"".isEmpty       // true
```

**不要使用`count`是否为0的方式来判断，这样会遍历整个字符串，性能差。**

### 如何判断空白字符串

有时候的需求是判断字符串是否是空白字符串，因为设计字符编码的问题，通常不好实现。

```swift
" "        // space
"\t\r\n"   // tab, return, newline
"\u{00a0}" // Unicode non-breaking space
"\u{2002}" // Unicode en space
"\u{2003}" // Unicode em space
```

通常的一些做法是，trim左右的空白，然后判断是否为空，但是swift中有更好的方式，可以使用[字符的属性](https://useyourloaf.com/blog/character-properties-in-swift-5/)， 类似这样。

```swift
func isBlank(_ string: String) -> Bool {
    for character in string {
        if !character.isWhitespace {
            return false
        }
    }
    return true
}
```

这样可以实现，但是更优雅的是，使用`allSatisfy`的方法。

```swift
"Hello".isBlank        // false
"   Hello   ".isBlank  // false
"".isBlank             // true
" ".isBlank            // true
"\t\r\n".isBlank       // true
"\u{00a0}".isBlank     // true
"\u{2002}".isBlank     // true
"\u{2003}".isBlank     // true
```

### 如何判断Optional的字符串
option类型字符串的判断，也可以写得很优雅。

```swift
extension Optional where Wrapped == String {
    var isBlank: Bool {
        return self?.isBlank ?? true
    }
}
```

```swift
var title: String? = nil
title.isBlank            // true
title = ""
title.isBlank            // true
title = "  \t  "
title.isBlank            // true
title = "Hello"
title.isBlank            // false
```

---

原文 / Source: <https://hicc.pro/p/blog/empty-strings-in-swift>
