0
1

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 3 years have passed since last update.

[Swift]Array から Dictionary への変換

Last updated at Posted at 2021-05-09

Struct Array から Dictionaryに変換処理(メモ)

1。reduce を利用し、変換

reduce(::)

指定されたクロージャを使用してシーケンスの要素を組み合わせた結果を返します。

func reduce<Result>(_ initialResult: Result,
                    _ nextPartialResult: (Result, Element) throws -> Result) 
                    rethrows -> Result

reduce(::) Developer Document 

code

dic1.swift
items.reduce([String: Item]()) { (dic, item) in
    var resultDic = dic
    resultDic[item.id] = item
    return resultDic
}

結果 [String, Item]
["3": Item(id: "3", title: "title3"),
"1": Item(id: "1", title: "title1"),
"2": Item(id: "2", title: "title2")]

2。Dictionary(uniqueKeysWithValues:) を利用し、変換①

init(uniqueKeysWithValues:)

指定された順序でキーと値のペアから新しい辞書を作成します。

//Creates a new dictionary from the key-value pairs in the given sequence.
init<S>(uniqueKeysWithValues keysAndValues: S) 
where S : Sequence, S.Element == (Key, Value)

init(uniqueKeysWithValues:) Developer Document

code

dic2.swift
Dictionary(uniqueKeysWithValues: items.map { item in
    (item.id, items.filter { $0.id == item.id }.first)
})

結果 [String, Item?]
["2": Optional(Item(id: "2", title: "title2")),
"3": Optional(Item(id: "3", title: "title3")),
"1": Optional(Item(id: "1", title: "title1"))]

3。Dictionary(uniqueKeysWithValues:) を利用し、変換②

collections zip(::)

2つの基礎となるシーケンスから構築されたペアのシーケンスを作成します。

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

collections zip(::) Developer Document

code

dic3.swift
Dictionary(uniqueKeysWithValues: zip(items.map {$0.id}, items))

結果 [String, Item]
["3": Item(id: "3", title: "title3"),
"1": Item(id: "1", title: "title1"),
"2": Item(id: "2", title: "title2")]

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?