12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftのCollectionsにおけるzipメソッドについて

Last updated at Posted at 2018-11-11

はじめに

SwiftのStandard Libraryに Collectionsのメソッドとしてzip(::)というものがあることを知りました。備忘もかねて記載します。

検証環境

以下の環境を使用しています。

  • macOS High Sierra Version 10.13.6
  • Xcode Version 10.0.0

Collectionsにおける zipメソッドについて

以下で定義されます。

func zip<Sequence1, Sequence2>(_ sequence1: Sequence1, _ sequence2: Sequence2) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence

ここで返却値であるZip2SequenceはSequence1、 Sequence2 から生成されるTupleのSequenceになります。例えば、下記のようになります。firstNamesの文字列配列とlastNamesの文字列配列から(String, String)のtupleの配列が生成されています。

let firstNames = ["Immanuel", "George", "Raymond"]
let lastNames = ["Kant", "Orwell", "Carver"]
let fullNames = zip(firstNames, lastNames)

fullNames.forEach { tuple in
    print(tuple)
}

// 出力
//("Immanuel", "Kant")
//("George", "Orwell")
//("Raymond", "Carver")

なお、上記は一つ目のSequenceと2つ目のSequenceが同数の場合の挙動ですが、要素数が異なる場合は下記のように少ない要素数に合わせてTupleのSequenceが生成されます。

let firstNames = ["Immanuel", "George", "Raymond"]
let lastNames = ["Kant", "Orwell", "Carver", "Троцкий"]
let fullNames = zip(firstNames, lastNames)

// lastNamesの最後の文字列が出力に含まれません
// 出力
//("Immanuel", "Kant")
//("George", "Orwell")
//("Raymond", "Carver")

考えられる使用用途

他にもたくさんあるかとは思いますが、下記の画像のようなUIを作成する際に、元のデータが2つの配列に別れているとします。そのような場合にはデータの挿入時にzipを使用するというのも選択肢の一つとして考えられるのではないでしょうか。
また2次元座標系のx, y の要素がそれぞれ配列で与えられており、そこから2次元座標の組みを作成するといった用途にも使えそうです。

スクリーンショット 2018-11-11 18.34.55.png

参考資料

12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?