Skip to content

Instantly share code, notes, and snippets.

@ANSCoder
Created August 22, 2021 14:21
Show Gist options
  • Save ANSCoder/23f173ffd96d41606d36060d35e6c359 to your computer and use it in GitHub Desktop.
Save ANSCoder/23f173ffd96d41606d36060d35e6c359 to your computer and use it in GitHub Desktop.
Unwrap values inside the SwiftUI `View`
//
// UnwrapUtil.swift
// Grocers
//
// Created by Anand Nimje on 08/09/20.
// Copyright © 2020 Anscoder. All rights reserved.
//
import SwiftUI
struct Unwrap<Value, Content: View>: View {
private let value: Value?
private let contentProvider: (Value) -> Content
init(_ value: Value?,
@ViewBuilder content: @escaping (Value) -> Content) {
self.value = value
self.contentProvider = content
}
var body: some View {
value.map(contentProvider)
}
}
@ANSCoder
Copy link
Author

Uses -
Working with the Optionals type models inside the SwiftUI

struct OrangeView: View {
    @ObservedObject var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Unwrap(self.viewModel.searchResult ?? []) { model in
                Grid(model,
                      columns: 2,
                      vSpacing: 8,
                      hSpacing: 8,
                      vPadding: 0) {
                        // Grid Cell
                }
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment