Published on

Dictionary在Swift中的一些常见用法

Authors
  • Name
    Twitter

在Swift中的Standard Library中定义了一些我们常用的数据结构,包括( Int Double String Array Dictionary)。在我们平时的编程过程中,或者在刷算法题Leecode的时候,能否训练使用这些类型,熟悉其基本操作,我认为是非常重要的事情。而这些基础往往在我们面试或者工作中,不太被重视的。所以我决定通过官方文档,来学习掌握它们。

这篇主要是讲 Dictionary 主要有下面几个章节

Creating a Dictionary

Inspecting a Dictionary

Accessing Keys and Values

Adding Keys and Values

Removing Keys and Values

Comparing Dictionaries

Iterating over Keys and Values

Finding Elements

  1. contains(where:)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate

func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool

语法分析: Self.Element 代表的是 Dictionary 中的元素类型 (Self.Element) throws -> Bool 代表形参 predicate 的类型是一个闭包 Closure throws 表示这个闭包可能会抛出错误 rethrows 表示闭包抛出的错误,实例方法 contains(where:) 如果捕获到了,会向上抛出。

示例:

enum HttpResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HttpResponse] = [.ok, .ok, .error(404)]

let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        // 这里的 if case 是一个模式匹配的用法,其实就是对 element 进行的一个单一枚举。
        return true
    } else {
        return false
    }
}

Transforming a Dictionary

Performing Collection Operations

Encoding and Decoding

Describing a Dictionary