3
3

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.

[SwiftUI] [String: [String]]をセクションで分けて表示する

Posted at

値が配列のDictionaryをセクションで分けて表示するレシピです。

let data: [String : [String]] = [
    "a" : ["a1", "a2", "a3"],
    "e" : ["e1", "e2", "e3"],
    "c" : ["c1", "c2", "c3"],
    "d" : ["d1", "d2", "d3"],
    "b" : ["b1", "b2", "b3"],

]

のようなデータある場合に、dataのkeyをセクションにしてその中身をrowとして表示します。

var body: some View {
    let keys: [String] = data.map { $0.key }
    let values: [[String]] = keys.compactMap { data[$0] }

    return List {
        ForEach(keys.indices) { (keyIndex) in
            Section(header: Text("\(keys[keyIndex])")) {
                ForEach(values[keyIndex].indices) { (valueIndex) in
                    Text(values[keyIndex][valueIndex])
                }
            }
        }
    }
}

dictionaryを直接ForEachで回すことが出来ないため事前にkeysとvaluesを作り、それらのindexでForEachをかけます。
注意点としてはvaluesも同様にdata.mapで作るとSwiftのDictionaryは順序保証がされていないので、keyの順序と矛盾します。必ずkeysの配列からvaluesを作ります。

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?