diff --git a/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift b/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift index 85763dc0..4624f0a0 100644 --- a/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift +++ b/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift @@ -5,9 +5,10 @@ struct DerivedBehaviorApp: App { var body: some Scene { WindowGroup { NavigationView { - AppView( - store: .init(initialState: AppState.init(counters: []), reducer: appReducer, environment: AppEnvironment(fact: .live, mainQueue: .main, uuid: UUID.init)) - ) +// AppView( +// store: .init(initialState: AppState.init(counters: []), reducer: appReducer, environment: AppEnvironment(fact: .live, mainQueue: .main, uuid: UUID.init)) +// ) + VanillaAppView(viewModel: AppViewModel(fact: .live, mainQueue: .main, uuid: UUID.init)) } } } diff --git a/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/VanillaView.swift b/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/VanillaView.swift index 5155fbd7..a2b6c9f7 100644 --- a/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/VanillaView.swift +++ b/0150-derived-behavior-pt5/DerivedBehavior/DerivedBehavior/VanillaView.swift @@ -80,21 +80,29 @@ struct VanillaCounterView: View { class CounterRowViewModel: ObservableObject, Identifiable { @Published var counter: CounterViewModel let id: UUID + let onRemove: () -> Void - init(counter: CounterViewModel, id: UUID) { + init( + counter: CounterViewModel, + id: UUID, + onRemove: @escaping () -> Void + ) { self.counter = counter self.id = id + self.onRemove = onRemove } func removeButtonTapped() { // TODO: track analytics + DispatchQueue.main.asyncAfter(deadline: .now() + 5) { + self.onRemove() + } } } struct VanillaCounterRowView: View { let viewModel: CounterRowViewModel - let onRemoveTapped: () -> Void - + var body: some View { HStack { VanillaCounterView( @@ -105,7 +113,6 @@ struct VanillaCounterRowView: View { Button("Remove") { withAnimation { - self.onRemoveTapped() self.viewModel.removeButtonTapped() } } @@ -197,6 +204,11 @@ struct VanillaFactPrompt: View { } } +struct IdentifiedArray { + var ids: [Element.ID] + var lookup: [Element.ID: Element] +} + class AppViewModel: ObservableObject { @Published var counters: [CounterRowViewModel] = [] @Published var factPrompt: FactPromptViewModel? @@ -237,10 +249,28 @@ class AppViewModel: ObservableObject { } ) + let id = self.uuid() +// let index = self.counters.endIndex self.counters.append( .init( counter: counterViewModel, - id: self.uuid() + id: id, + onRemove: { [weak self] in + + // - quick lookup / in-place mutation + // - handles invariants for duplicate identities + // - simpler than ordered set (requires hashable elements) + +// self?.counters.removeAll(where: { $0.id == id }) + guard let self = self else { return } + for (index, counter) in zip(self.counters.indices, self.counters) { + if counter.id == id { + self.counters.remove(at: index) + return + } + } +// self?.counters.remove(at: index) + } ) ) @@ -249,10 +279,6 @@ class AppViewModel: ObservableObject { .store(in: &self.cancellables) } - func removeButtonTapped(id: UUID) { - self.counters.removeAll(where: { $0.id == id }) - } - func dismissFactPrompt() { self.factPrompt = nil } @@ -268,10 +294,7 @@ struct VanillaAppView: View { ForEach(self.viewModel.counters) { counterRow in VanillaCounterRowView( - viewModel: counterRow, - onRemoveTapped: { - self.viewModel.removeButtonTapped(id: counterRow.id) - } + viewModel: counterRow ) } } diff --git a/0151-tca-performance/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift b/0151-tca-performance/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift index f3d0e24d..e92a5327 100644 --- a/0151-tca-performance/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift +++ b/0151-tca-performance/DerivedBehavior/DerivedBehavior/DerivedBehaviorApp.swift @@ -1,21 +1,17 @@ -// -// DerivedBehaviorApp.swift -// DerivedBehavior -// -// Created by Point-Free on 5/12/21. -// - +import ComposableArchitecture import SwiftUI @main struct DerivedBehaviorApp: App { - var body: some Scene { - WindowGroup { - VanillaContentView( - viewModel: .init() -// counterViewModel: .init(), -// profileViewModel: .init() - ) - } + var body: some Scene { + WindowGroup { + TcaContentView( + store: Store( + initialState: .init(), + reducer: appReducer, + environment: .init() + ) + ) } + } } diff --git a/0152-case-paths-performance/README.md b/0152-case-paths-performance/README.md new file mode 100644 index 00000000..762f0290 --- /dev/null +++ b/0152-case-paths-performance/README.md @@ -0,0 +1,7 @@ +## [Point-Free](https://www.pointfree.co) + +> #### This directory contains code from Point-Free Episode: [Composable Architecture Performance: Case Paths](https://www.pointfree.co/episodes/ep152-composable-architecture-performance-case-paths) +> +> This week we improve the performance of another part of the Composable Architecture ecosystem: case paths! We will benchmark the reflection mechanism that powers case paths and speed things up with the help of a Swift runtime function. + +For the section of the episode where we refactor the Case Paths, see [this GitHub pull request](https://github.com/pointfreeco/swift-case-paths/pull/35). diff --git a/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.pbxproj b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.pbxproj new file mode 100644 index 00000000..223cea95 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.pbxproj @@ -0,0 +1,368 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 52; + objects = { + +/* Begin PBXBuildFile section */ + 2AC9838926A0ABFF00A5812A /* Refreshable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AC9838826A0ABFE00A5812A /* Refreshable.swift */; }; + DC13940E2469E25C00EE1157 /* ComposableArchitecture in Frameworks */ = {isa = PBXBuildFile; productRef = DC13940D2469E25C00EE1157 /* ComposableArchitecture */; }; + DC5140D826A5B88000BBF398 /* ComposableArchitecture in Frameworks */ = {isa = PBXBuildFile; productRef = DC5140D726A5B88000BBF398 /* ComposableArchitecture */; }; + DC89C41924460F95006900B9 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC89C41824460F95006900B9 /* SceneDelegate.swift */; }; + DC89C41D24460F96006900B9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = DC89C41C24460F96006900B9 /* Assets.xcassets */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + DC89C43D2446106D006900B9 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 2AC9838826A0ABFE00A5812A /* Refreshable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Refreshable.swift; sourceTree = ""; }; + DC89C41324460F95006900B9 /* SwiftUICaseStudies.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftUICaseStudies.app; sourceTree = BUILT_PRODUCTS_DIR; }; + DC89C41824460F95006900B9 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + DC89C41C24460F96006900B9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + DC89C42424460F96006900B9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + DC89C41024460F95006900B9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DC5140D826A5B88000BBF398 /* ComposableArchitecture in Frameworks */, + DC13940E2469E25C00EE1157 /* ComposableArchitecture in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + DC89C40A24460F95006900B9 = { + isa = PBXGroup; + children = ( + DC89C43A2446106D006900B9 /* Frameworks */, + DC89C41424460F95006900B9 /* Products */, + DC89C41524460F95006900B9 /* SwiftUICaseStudies */, + ); + sourceTree = ""; + }; + DC89C41424460F95006900B9 /* Products */ = { + isa = PBXGroup; + children = ( + DC89C41324460F95006900B9 /* SwiftUICaseStudies.app */, + ); + name = Products; + sourceTree = ""; + }; + DC89C41524460F95006900B9 /* SwiftUICaseStudies */ = { + isa = PBXGroup; + children = ( + DC89C42424460F96006900B9 /* Info.plist */, + DC89C41824460F95006900B9 /* SceneDelegate.swift */, + DC89C41C24460F96006900B9 /* Assets.xcassets */, + 2AC9838826A0ABFE00A5812A /* Refreshable.swift */, + ); + path = SwiftUICaseStudies; + sourceTree = ""; + }; + DC89C43A2446106D006900B9 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + DC89C41224460F95006900B9 /* SwiftUICaseStudies */ = { + isa = PBXNativeTarget; + buildConfigurationList = DC89C43224460F96006900B9 /* Build configuration list for PBXNativeTarget "SwiftUICaseStudies" */; + buildPhases = ( + DC89C40F24460F95006900B9 /* Sources */, + DC89C41024460F95006900B9 /* Frameworks */, + DC89C41124460F95006900B9 /* Resources */, + DC89C43D2446106D006900B9 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftUICaseStudies; + packageProductDependencies = ( + DC13940D2469E25C00EE1157 /* ComposableArchitecture */, + DC5140D726A5B88000BBF398 /* ComposableArchitecture */, + ); + productName = CaseStudies; + productReference = DC89C41324460F95006900B9 /* SwiftUICaseStudies.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + DC89C40B24460F95006900B9 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1150; + LastUpgradeCheck = 1240; + ORGANIZATIONNAME = "Point-Free"; + TargetAttributes = { + DC89C41224460F95006900B9 = { + CreatedOnToolsVersion = 11.4; + }; + }; + }; + buildConfigurationList = DC89C40E24460F95006900B9 /* Build configuration list for PBXProject "CaseStudies" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = DC89C40A24460F95006900B9; + packageReferences = ( + DC5140D626A5B88000BBF398 /* XCRemoteSwiftPackageReference "swift-composable-architecture" */, + ); + productRefGroup = DC89C41424460F95006900B9 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + DC89C41224460F95006900B9 /* SwiftUICaseStudies */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + DC89C41124460F95006900B9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DC89C41D24460F96006900B9 /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + DC89C40F24460F95006900B9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DC89C41924460F95006900B9 /* SceneDelegate.swift in Sources */, + 2AC9838926A0ABFF00A5812A /* Refreshable.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + DC89C43024460F96006900B9 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + DC89C43124460F96006900B9 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + DC89C43324460F96006900B9 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = SwiftUICaseStudies/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.SwiftUICaseStudies; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + DC89C43424460F96006900B9 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = SwiftUICaseStudies/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.SwiftUICaseStudies; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + DC89C40E24460F95006900B9 /* Build configuration list for PBXProject "CaseStudies" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DC89C43024460F96006900B9 /* Debug */, + DC89C43124460F96006900B9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + DC89C43224460F96006900B9 /* Build configuration list for PBXNativeTarget "SwiftUICaseStudies" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DC89C43324460F96006900B9 /* Debug */, + DC89C43424460F96006900B9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + DC5140D626A5B88000BBF398 /* XCRemoteSwiftPackageReference "swift-composable-architecture" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/pointfreeco/swift-composable-architecture.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 0.21.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + DC13940D2469E25C00EE1157 /* ComposableArchitecture */ = { + isa = XCSwiftPackageProductDependency; + productName = ComposableArchitecture; + }; + DC5140D726A5B88000BBF398 /* ComposableArchitecture */ = { + isa = XCSwiftPackageProductDependency; + package = DC5140D626A5B88000BBF398 /* XCRemoteSwiftPackageReference "swift-composable-architecture" */; + productName = ComposableArchitecture; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = DC89C40B24460F95006900B9 /* Project object */; +} diff --git a/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (SwiftUI).xcscheme b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (SwiftUI).xcscheme new file mode 100644 index 00000000..7cd4593a --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (SwiftUI).xcscheme @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (UIKit).xcscheme b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (UIKit).xcscheme new file mode 100644 index 00000000..50d8ea9e --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/CaseStudies.xcodeproj/xcshareddata/xcschemes/CaseStudies (UIKit).xcscheme @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/AppIcon.png new file mode 100644 index 00000000..186b90e3 Binary files /dev/null and b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/Contents.json b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..e4b96da0 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,99 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "filename" : "AppIcon.png", + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/Contents.json b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Info.plist b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Info.plist new file mode 100644 index 00000000..162e5aaa --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Info.plist @@ -0,0 +1,65 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + + + + + UILaunchStoryboardName + LaunchScreen + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Refreshable.swift b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Refreshable.swift new file mode 100644 index 00000000..014fb89f --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/Refreshable.swift @@ -0,0 +1,93 @@ +import SwiftUI + +class PullToRefreshViewModel: ObservableObject { + @Published var count = 0 + @Published var fact: String? = nil + + @Published private var task: Task? + let fetch: (Int) async throws -> String + + init(fetch: @escaping (Int) async throws -> String) { + self.fetch = fetch + } + + var isLoading: Bool { + self.task != nil + } + + func incrementButtonTapped() { + self.count += 1 + } + + func decrementButtonTapped() { + self.count -= 1 + } + + @MainActor + func getFact() async { + self.fact = nil + + self.task = Task { + try await self.fetch(self.count) + } + defer { self.task = nil } + + do { + let fact = try await task?.value + withAnimation { + self.fact = fact + } + + } catch { + // TODO: do some error handling + } + } + + func cancelButtonTapped() { + self.task?.cancel() + self.task = nil + } +} + +struct VanillaPullToRefreshView: View { + @ObservedObject var viewModel: PullToRefreshViewModel + + var body: some View { + List { + HStack { + Button("-") { self.viewModel.decrementButtonTapped() } + Text("\(self.viewModel.count)") + Button("+") { self.viewModel.incrementButtonTapped() } + } + .buttonStyle(.plain) + + if let fact = self.viewModel.fact { + Text(fact) + } + if self.viewModel.isLoading { + Button("Cancel") { + self.viewModel.cancelButtonTapped() + } + } + } + .refreshable { + await self.viewModel.getFact() + } + } +} + +struct VanillaPullToRefreshView_Previews: PreviewProvider { + static var previews: some View { + VanillaPullToRefreshView( + viewModel: .init( + fetch: { count in + await Task.sleep(2 * NSEC_PER_SEC) + + let (data, _) = try await URLSession.shared.data(from: .init(string: "http://numbersapi.com/\(count)/trivia")!) + + return String(decoding: data, as: UTF8.self) + } + ) + ) + } +} diff --git a/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/SceneDelegate.swift b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/SceneDelegate.swift new file mode 100644 index 00000000..72a53f13 --- /dev/null +++ b/0153-refreshable-pt1/CaseStudies/SwiftUICaseStudies/SceneDelegate.swift @@ -0,0 +1,38 @@ +import SwiftUI +import UIKit + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + self.window = (scene as? UIWindowScene).map(UIWindow.init(windowScene:)) + self.window?.rootViewController = UIHostingController( + rootView: VanillaPullToRefreshView( + viewModel: .init( + fetch: { count in + await Task.sleep(2 * NSEC_PER_SEC) + + let (data, _) = try await URLSession.shared.data(from: .init(string: "http://numbersapi.com/\(count)/trivia")!) + + return String(decoding: data, as: UTF8.self) + } + ) + ) + ) + self.window?.makeKeyAndVisible() + } +} + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + true + } +} diff --git a/0153-refreshable-pt1/README.md b/0153-refreshable-pt1/README.md new file mode 100644 index 00000000..1bee974b --- /dev/null +++ b/0153-refreshable-pt1/README.md @@ -0,0 +1,5 @@ +## [Point-Free](https://www.pointfree.co) + +> #### This directory contains code from Point-Free Episode: [Async Refreshable: SwiftUI](https://www.pointfree.co/episodes/ep153-async-refreshable-swiftui) +> +> Let’s take a look at the new refreshable API in SwiftUI. We will explore how to add it to a feature, how it depends on Swift’s new async/await tools, and how to introduce cancellation.