Skip to content

Instantly share code, notes, and snippets.

@kieranb662
Last active June 29, 2020 17:53
Show Gist options
  • Save kieranb662/8d89314ee3cfc4c5451f5a3ccd1006bb to your computer and use it in GitHub Desktop.
Save kieranb662/8d89314ee3cfc4c5451f5a3ccd1006bb to your computer and use it in GitHub Desktop.
[SwiftUI var vs func] A quick explanation of when I think it Is more useful to return a View from a computed variable or a function and vice versa. #SwiftUI
//
// ContentView.swift
// SwiftUIVarVsFunc
//
// Created by Kieran Brown on 11/1/19.
// Copyright © 2019 Kieran Brown. All rights reserved.
//
import SwiftUI
/// Example of when to use a computed variable to return a view
/// I think I should describe the "general" reasons I think it would be better to use a computed variable instead of a function.
/// 1. The View is styled in a specific way but used in mutliple locations.
/// 2. Nothing depends on input from within a Viewbuilder closure.
/// 3. Slightly more convienent because you dont need to input dummy values that you might need to input with a general function.
struct ComputedVariableExample: View {
// 1, 2, 3
var bigRedHello: some View {
Text("Hello")
.font(.largeTitle)
.foregroundColor(.red)
}
var body: some View {
HStack {
bigRedHello
Circle()
bigRedHello
}
}
}
/// Example when function would be more useful
/// 1. When a geometry proxy needs to be passed from within a body.
/// 2. When you need to change certain aspects of a reusable view.
struct FunctionExample: View {
// 1
func circleThatChangesColorWithSize(proxy: GeometryProxy) -> some View {
Circle()
.foregroundColor(proxy.size.height > 400 ? Color.blue : Color.red)
}
// 2
func purpleRectangleWithText(_ text: String) -> some View {
Rectangle()
.foregroundColor(.purple)
.overlay(Text(text))
}
var body: some View {
VStack {
GeometryReader { (proxy: GeometryProxy) in
self.circleThatChangesColorWithSize(proxy: proxy)
}
purpleRectangleWithText("What up square?")
}
}
}
// Comment out the line ComputedVariableExample() to watch the red circle change to blue because its container increased size.
struct ContentView: View {
var body: some View {
VStack {
ComputedVariableExample()
FunctionExample()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment