Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CodeSlicing/bce4241e1a535ec2c094564355d40de3 to your computer and use it in GitHub Desktop.
Save CodeSlicing/bce4241e1a535ec2c094564355d40de3 to your computer and use it in GitHub Desktop.
Source code for CodeSlicing episode on Property Wrappers Part 04: Age Validation with a Property Wrapper
//
// EditingUserWithAgeValidationDemo.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Created by Adam Fordyce on 04/06/2021.
// Copyright © 2020 Adam Fordyce. All rights reserved.
//
import SwiftUI
import PureSwiftUI
private let defaultUsers: [User] = [
User(name: "Anthony", age: 53),
User(name: "Emilio", age: 59),
User(name: "Ally", age: 58),
User(name: "Molly", age: 53),
User(name: "Judd", age: 61),
]
private class AppState: ObservableObject {
@Published var users: [User] = defaultUsers
}
private struct User: Equatable, Identifiable {
var id = UUID()
@Clamped(from: "Adam", to: "David") var name = "Adam"
@Clamped(from: 0, to: 100) var age = 0
}
@propertyWrapper
private struct Clamped<T: Comparable>: Equatable {
private let from: T?
private let to: T?
private var _wrappedValue: T
init(wrappedValue: T, from: T? = nil, to: T? = nil) {
self.from = from
self.to = to
self._wrappedValue = wrappedValue.clamped(from: from, to: to)
}
var wrappedValue: T {
get {
_wrappedValue
}
set {
_wrappedValue = newValue.clamped(from: from, to: to)
}
}
static func == (lhs: Self, rhs: Self) -> Bool {
lhs._wrappedValue == rhs._wrappedValue
}
}
struct EditingUserWithAgeValidationDemo: View {
@StateObject private var appState = AppState()
@State private var showingEditScreen = false
var body: some View {
NavigationView {
List(0..<appState.users.count) { index in
NavigationLink(destination: EditUser(user: appState.users[index]) { user in
appState.users[index] = user
}) {
let user = appState.users[index]
TitleText("\(user.name): \(user.age)")
}
}
.navigationTitle("Breakfast Rota")
}
}
}
private struct EditUser: View {
@Environment(\.presentationMode) var presentationMode
@State var user: User
let saveHandler: (User) -> ()
init(user: User, saveHandler: @escaping (User) -> ()) {
_user = State(initialValue: user)
self.saveHandler = saveHandler
}
var body: some View {
ZStack {
VStack(spacing: 50) {
ZStack {
TextField("Name", text: $user.name)
.font(.title)
.hPadding(8)
.padding()
.clipCapsuleWithStroke(Color.white, lineWidth: 2)
}
HStack(spacing: 20) {
CounterButton(sfSymbol: .chevron_left_2) {
user.age -= 10
}
CounterButton(sfSymbol: .chevron_left) {
user.age -= 1
}
TitleText("\(user.age)")
.width(75)
.padding()
.clipCapsuleWithStroke(Color.white, lineWidth: 2)
CounterButton(sfSymbol: .chevron_right) {
user.age += 1
}
CounterButton(sfSymbol: .chevron_right_2) {
user.age += 10
}
}
HStack {
ActionButton(sfSymbol: .xmark, color: Color.red.opacity(0.5)) {
dismissPopover()
}
Spacer()
ActionButton(sfSymbol: .checkmark, color: Color.green.opacity(0.5)) {
saveHandler(user)
dismissPopover()
}
}
}
}
.padding(50)
.demoPageStyling()
}
private func dismissPopover() {
presentationMode.wrappedValue.dismiss()
}
}
private struct CounterButton: View {
let sfSymbol: SFSymbolName
let handler: () -> ()
var body: some View {
Button {
handler()
} label: {
addSFSymbol(sfSymbol)
}
}
}
private struct ActionButton: View {
let sfSymbol: SFSymbolName
let color: Color
let handler: () -> ()
var body: some View {
Button {
handler()
} label: {
addSFSymbol(sfSymbol)
.frame(120, 75)
.clipCapsuleWithStroke(Color.white, lineWidth: 2, fill: color)
}
}
}
// MARK: ----- EXTENSIONS
private extension View {
func addSFSymbol(_ sfSymbol: SFSymbolName) -> some View {
SFSymbol(sfSymbol)
.font(.system(size: 35, weight: .light))
}
func demoPageStyling() -> some View {
greedyFrame()
.foregroundColor(.white)
.backgroundColor(.white(0.1))
.ignoresSafeArea()
}
}
private extension Int {
func clamped(from: Int, to: Int) -> Int {
Swift.max(from, Swift.min(to, self))
}
}
private extension Comparable {
func clamped(from: Self?, to: Self?) -> Self {
var clampedValue = self
if let from = from {
clampedValue = max(from, clampedValue)
}
if let to = to {
clampedValue = min(to, clampedValue)
}
return clampedValue
}
}
struct EditingUserWithAgeValidationDemo_Previews: PreviewProvider {
struct EditingUserWithAgeValidationDemo_Harness: View {
var body: some View {
EditingUserWithAgeValidationDemo()
.demoPageStyling()
.envDarkMode()
}
}
static var previews: some View {
EditingUserWithAgeValidationDemo_Harness()
.previewDevice(.iPhone_12_Pro_Max)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment