Splat.swift 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // Splat.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 4/15/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import SwiftUI
  9. /// A structure representing multiple components of one `Card`.
  10. ///
  11. /// Use `Splat` to intermix static and dynamic card components:
  12. /// ```
  13. /// Card {
  14. /// Text("Above dynamic data")
  15. /// Splat(1...5, id: \.self) { value in
  16. /// Text("Dynamic data \(value)")
  17. /// }
  18. /// Text("Below dynamic data")
  19. /// }
  20. /// ```
  21. public struct Splat: View {
  22. var identifiedViews: [(view: AnyView, id: AnyHashable)]
  23. public init<Data: RandomAccessCollection, ID: Hashable, Content: View>(
  24. _ data: Data,
  25. id: KeyPath<Data.Element, ID>,
  26. @ViewBuilder rowContent: (Data.Element) -> Content
  27. ) {
  28. identifiedViews = data.map { datum in
  29. (view: AnyView(rowContent(datum)), id: datum[keyPath: id])
  30. }
  31. }
  32. public init<Data: RandomAccessCollection, Content: View>(
  33. _ data: Data,
  34. @ViewBuilder rowContent: (Data.Element) -> Content
  35. ) where Data.Element: Identifiable {
  36. self.init(data, id: \.id, rowContent: rowContent)
  37. }
  38. public var body: some View {
  39. Card(components: [.dynamic(identifiedViews)])
  40. }
  41. }