changeset 47:75c1a05176f6

Refactor code
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Mon, 26 Jul 2021 20:08:20 +0100
parents ce4eb7416b41
children 67e76ce661a1
files Simoleon.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate Simoleon.xcodeproj/xcuserdata/dennis.xcuserdatad/xcschemes/xcschememanagement.plist Simoleon/Conversion.swift Simoleon/Favourites.swift Simoleon/Functions/ParseJson.swift Simoleon/Functions/ReadConfig.swift Simoleon/Functions/SimpleSuccess.swift Simoleon/Helpers/ConditionalWrapper.swift Simoleon/Helpers/ConversionBox.swift Simoleon/Helpers/CurrencySelector.swift Simoleon/Helpers/FavouriteButton.swift Simoleon/Helpers/SubscribeButton.swift Simoleon/Models/DefaultCurrency+CoreDataClass.swift Simoleon/Models/DefaultCurrency+CoreDataProperties.swift Simoleon/Models/Favourite+CoreDataClass.swift Simoleon/Models/Favourite+CoreDataProperties.swift Simoleon/Persistence.swift Simoleon/Settings.swift Simoleon/SimoleonApp.swift Simoleon/SubscriptionPaywall.swift
diffstat 20 files changed, 128 insertions(+), 100 deletions(-) [+]
line wrap: on
line diff
Binary file Simoleon.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate has changed
--- a/Simoleon.xcodeproj/xcuserdata/dennis.xcuserdatad/xcschemes/xcschememanagement.plist	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon.xcodeproj/xcuserdata/dennis.xcuserdatad/xcschemes/xcschememanagement.plist	Mon Jul 26 20:08:20 2021 +0100
@@ -4,10 +4,31 @@
 <dict>
 	<key>SchemeUserState</key>
 	<dict>
+		<key>SWXMLHashPlayground (Playground) 1.xcscheme</key>
+		<dict>
+			<key>isShown</key>
+			<false/>
+			<key>orderHint</key>
+			<integer>2</integer>
+		</dict>
+		<key>SWXMLHashPlayground (Playground) 2.xcscheme</key>
+		<dict>
+			<key>isShown</key>
+			<false/>
+			<key>orderHint</key>
+			<integer>3</integer>
+		</dict>
+		<key>SWXMLHashPlayground (Playground).xcscheme</key>
+		<dict>
+			<key>isShown</key>
+			<false/>
+			<key>orderHint</key>
+			<integer>0</integer>
+		</dict>
 		<key>Simoleon.xcscheme_^#shared#^_</key>
 		<dict>
 			<key>orderHint</key>
-			<integer>0</integer>
+			<integer>1</integer>
 		</dict>
 	</dict>
 </dict>
--- a/Simoleon/Conversion.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Conversion.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -73,10 +73,10 @@
         let url = "\(readConfig("API_URL")!)quotes?pairs=\(currencyPair)&api_key=\(readConfig("API_KEY")!)"
         
         Simoleon.request(url: url, model: [CurrencyQuoteModel].self) { response in
-            self.showingConversion = false
+            showingConversion = false
             if let price = response.first?.price {
                 self.price = price
-                self.showingConversion =  true
+                showingConversion =  true
             } else {
                 // Handle error
             }
--- a/Simoleon/Favourites.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Favourites.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -48,7 +48,7 @@
     private func removeFromFavourites(offsets: IndexSet) {
         withAnimation {
             offsets.map { favourite[$0] }.forEach(viewContext.delete)
-
+            
             do {
                 try viewContext.save()
             } catch {
--- a/Simoleon/Functions/ParseJson.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Functions/ParseJson.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -8,15 +8,13 @@
 import Foundation
 
 
-/*
- Read JSON File
- */
+// Read JSON File
 func parseJson<T: Decodable>(_ filename: String) -> T {
     let data: Data
     
     guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
-        else {
-            fatalError("Couldn't find \(filename) in main bundle.")
+    else {
+        fatalError("Couldn't find \(filename) in main bundle.")
     }
     
     do {
--- a/Simoleon/Functions/ReadConfig.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Functions/ReadConfig.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -8,6 +8,6 @@
 import SwiftUI
 
 func readConfig(_ key: String) -> String? {
-        return (Bundle.main.infoDictionary?[key] as? String)?
-            .replacingOccurrences(of: "\\", with: "")
- }
+    return (Bundle.main.infoDictionary?[key] as? String)?
+        .replacingOccurrences(of: "\\", with: "")
+}
--- a/Simoleon/Functions/SimpleSuccess.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Functions/SimpleSuccess.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -7,9 +7,7 @@
 
 import SwiftUI
 
-/*
- Haptics
- */
+// Haptics
 func simpleSuccess() {
     let generator = UINotificationFeedbackGenerator()
     generator.notificationOccurred(.success)
--- a/Simoleon/Helpers/ConditionalWrapper.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Helpers/ConditionalWrapper.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -8,8 +8,8 @@
 import SwiftUI
 
 extension View {
-   @ViewBuilder
-   func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
+    @ViewBuilder
+    func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
         if conditional {
             content(self)
         } else {
--- a/Simoleon/Helpers/ConversionBox.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Helpers/ConversionBox.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -26,17 +26,17 @@
             
             ZStack(alignment: .trailing) {
                 TextField("Enter amount", text: $amountToConvert) { startedEditing in
-                if startedEditing {
-                         withAnimation {
+                    if startedEditing {
+                        withAnimation {
                             amountIsEditing = true
-                         }
-                     }
+                        }
+                    }
                 }
                 onCommit: {
-                     withAnimation {
+                    withAnimation {
                         amountIsEditing = false
-                     }
-                 }
+                    }
+                }
                 .keyboardType(.decimalPad)
                 .font(Font.title.weight(.semibold))
                 .lineLimit(1)
@@ -63,12 +63,14 @@
     }
     
     /*
-     if the amount can be converted to Double -> return amount
-     else -> return zero
+     if the amount can be converted to Double:
+     * Return amount
+     else:
+     * Return zero
      */
     private func makeConversion() -> Double {
         if let amountToConvert = Double(amountToConvert) {
-            return amountToConvert * price  /// Conversion
+            return amountToConvert * price  // Conversion
         } else {
             return 0
         }
--- a/Simoleon/Helpers/CurrencySelector.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Helpers/CurrencySelector.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -30,10 +30,10 @@
                 }
             }
             .gesture(DragGesture()
-                 .onChanged({ _ in
-                    UIApplication.shared.dismissKeyboard()
-                 })
-             )
+                        .onChanged({ _ in
+                            UIApplication.shared.dismissKeyboard()
+                        })
+            )
             .sheet(isPresented: $showingSubscriptionPaywall) {
                 SubscriptionPaywall(showingSubscriptionPaywall: $showingSubscriptionPaywall)
             }
@@ -50,8 +50,10 @@
     }
     
     /*
-     If searched currency string is empty -> show all currencies
-     else -> show filtered list of currencies containing searched currency string
+     If searched currency string is empty:
+     * Show all currencies
+     else:
+     * Show filtered list of currencies containing searched currency string
      */
     private func currencyPairs() -> [String] {
         let currencyPairs: [String] = parseJson("CurrencyPairs.json")
@@ -65,24 +67,26 @@
     
     
     /*
-     If user is subscribed -> select currency and dismiss currency selector
-     else -> show subscription paywall
+     If user is subscribed:
+     * Select currency and dismiss currency selector
+     else:
+     * Show subscription paywall
      */
     private func select(_ currencyPair: String) {
         #if targetEnvironment(simulator)
-            // We're in simulator
-            self.currencyPair = currencyPair
-            showingCurrencySelector = false
+        // We're in simulator
+        self.currencyPair = currencyPair
+        showingCurrencySelector = false
         #else
-            // We're in physical device
-            Purchases.shared.purchaserInfo { (purchaserInfo, error) in
-                if purchaserInfo?.entitlements["all"]?.isActive == true {
-                    self.currencyPair = currencyPair
-                    showingCurrencySelector = false
-                } else {
-                    showingSubscriptionPaywall = true
-                }
+        // We're in physical device
+        Purchases.shared.purchaserInfo { (purchaserInfo, error) in
+            if purchaserInfo?.entitlements["all"]?.isActive == true {
+                self.currencyPair = currencyPair
+                showingCurrencySelector = false
+            } else {
+                showingSubscriptionPaywall = true
             }
+        }
         #endif
     }
 }
--- a/Simoleon/Helpers/FavouriteButton.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Helpers/FavouriteButton.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -29,8 +29,10 @@
     }
     
     /*
-     If currency pair is favourite -> button action is to remove from favourites
-     else -> button action is to add to favourites
+     If currency pair is favourite:
+     * Button action is to remove from favourites
+     else:
+     * Button action is to add to favourites
      */
     private func favouriteAction(_ favouriteCurrencyPairs: [String]) {
         if favouriteCurrencyPairs.contains(currencyPair) {
@@ -43,8 +45,10 @@
     }
     
     /*
-     if currency pair is favourite -> return "star.fill" symbol
-     else -> return "star"
+     if currency pair is favourite:
+     * Return "star.fill" symbol
+     else:
+     * Return "star"
      */
     private func generateStar(_ favouriteCurrencyPairs: [String]) -> String {
         if favouriteCurrencyPairs.contains(currencyPair) {
@@ -55,8 +59,8 @@
     }
     
     /*
-     1) Get first favourite core data object that matches the specified currency pair
-     2) Delete it
+     * Get first favourite core data object that matches the specified currency pair
+     * Delete it
      */
     private func removeFromFavourites() {
         withAnimation {
@@ -73,8 +77,8 @@
     }
     
     /*
-     1) Create a favourite core data object
-     2) Save it
+     * Create a favourite core data object
+     * Save it
      */
     private func addToFavourites() {
         withAnimation {
--- a/Simoleon/Helpers/SubscribeButton.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Helpers/SubscribeButton.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -42,7 +42,7 @@
     private func fetchMonthlySubscription() {
         Purchases.shared.offerings { (offerings, error) in
             if let product = offerings?.current?.monthly?.product {
-                self.price = formatCurrency(product.priceLocale, product.price)
+                price = formatCurrency(product.priceLocale, product.price)
                 showingPrice = true
             }
             
--- a/Simoleon/Models/DefaultCurrency+CoreDataClass.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Models/DefaultCurrency+CoreDataClass.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -11,5 +11,5 @@
 
 @objc(DefaultCurrency)
 public class DefaultCurrency: NSManagedObject {
-
+    
 }
--- a/Simoleon/Models/DefaultCurrency+CoreDataProperties.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Models/DefaultCurrency+CoreDataProperties.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -11,11 +11,11 @@
 
 
 extension DefaultCurrency {
-
+    
     @nonobjc public class func fetchRequest() -> NSFetchRequest<DefaultCurrency> {
         return NSFetchRequest<DefaultCurrency>(entityName: "DefaultCurrency")
     }
-
+    
     @NSManaged public var pair: String?
-
+    
 }
--- a/Simoleon/Models/Favourite+CoreDataClass.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Models/Favourite+CoreDataClass.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -11,5 +11,5 @@
 
 @objc(Favourite)
 public class Favourite: NSManagedObject {
-
+    
 }
--- a/Simoleon/Models/Favourite+CoreDataProperties.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Models/Favourite+CoreDataProperties.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -11,15 +11,15 @@
 
 
 extension Favourite {
-
+    
     @nonobjc public class func fetchRequest() -> NSFetchRequest<Favourite> {
         return NSFetchRequest<Favourite>(entityName: "Favourite")
     }
-
+    
     @NSManaged public var currencyPair: String
-
+    
 }
 
 extension Favourite : Identifiable {
-
+    
 }
--- a/Simoleon/Persistence.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Persistence.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -9,7 +9,7 @@
 
 struct PersistenceController {
     static let shared = PersistenceController()
-
+    
     static var preview: PersistenceController = {
         let result = PersistenceController(inMemory: true)
         let viewContext = result.container.viewContext
@@ -32,9 +32,9 @@
         }
         return result
     }()
-
+    
     let container: NSPersistentCloudKitContainer
-
+    
     init(inMemory: Bool = false) {
         container = NSPersistentCloudKitContainer(name: "Simoleon")
         container.viewContext.automaticallyMergesChangesFromParent = true
@@ -46,15 +46,15 @@
             if let error = error as NSError? {
                 // Replace this implementation with code to handle the error appropriately.
                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
-
+                
                 /*
-                Typical reasons for an error here include:
-                * The parent directory does not exist, cannot be created, or disallows writing.
-                * The persistent store is not accessible, due to permissions or data protection when the device is locked.
-                * The device is out of space.
-                * The store could not be migrated to the current model version.
-                Check the error message to determine what the actual problem was.
-                */
+                 Typical reasons for an error here include:
+                 * The parent directory does not exist, cannot be created, or disallows writing.
+                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
+                 * The device is out of space.
+                 * The store could not be migrated to the current model version.
+                 Check the error message to determine what the actual problem was.
+                 */
                 fatalError("Unresolved error \(error), \(error.userInfo)")
             }
         })
--- a/Simoleon/Settings.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/Settings.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -83,11 +83,15 @@
         .onAppear {
             checkEntitlement()
             /*
-             if selectedDefaultCurrency is empty -> view is appearing for the first time -> set initial default curency for picker
-             else -> view is appearing after user selected another default currency -> save it to core data
+             if selectedDefaultCurrency is empty:
+             * View is appearing for the first time
+             * Set initial default curency for picker
+             else:
+             * View is appearing after user selected another default currency
+             * Save it to core data
              */
             if selectedDefaultCurrency == "" {
-                self.selectedDefaultCurrency = defaultCurrency.first?.pair ?? "USD/GBP"
+                selectedDefaultCurrency = defaultCurrency.first?.pair ?? "USD/GBP"
             } else {
                 setCoreData()
             }
@@ -102,11 +106,10 @@
         }
     }
     
-    /*
-     Save default currency to core data
-     */
+     
+    // Save default currency to core data
     private func setCoreData() {
-        if self.defaultCurrency.isEmpty {  // If it's empty -> add record
+        if defaultCurrency.isEmpty {  // If it's empty -> add record
             let defaultCurrency = DefaultCurrency(context: viewContext)
             defaultCurrency.pair = selectedDefaultCurrency
             
@@ -116,28 +119,26 @@
                 print(error.localizedDescription)
             }
         } else {  // If not, update record
-            self.defaultCurrency.first?.pair = selectedDefaultCurrency
+            defaultCurrency.first?.pair = selectedDefaultCurrency
             try? viewContext.save()
         }
     }
     
-    /*
-     Check if user subscription is active
-     */
+    // Check if user subscription is active
     private func checkEntitlement() {
         #if targetEnvironment(simulator)
-            // We're in simulator
-            entitlementIsActive = true
+        // We're in simulator
+        entitlementIsActive = true
         #else
-            Purchases.shared.purchaserInfo { (purchaserInfo, error) in
-                if purchaserInfo?.entitlements["all"]?.isActive == true {
-                    entitlementIsActive = true
-                    print("Entitlement is active")
-                } else {
-                    entitlementIsActive = false
-                    print("Entitlement is NOT active")
-                }
+        Purchases.shared.purchaserInfo { (purchaserInfo, error) in
+            if purchaserInfo?.entitlements["all"]?.isActive == true {
+                entitlementIsActive = true
+                print("Entitlement is active")
+            } else {
+                entitlementIsActive = false
+                print("Entitlement is NOT active")
             }
+        }
         #endif
     }
 }
--- a/Simoleon/SimoleonApp.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/SimoleonApp.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -12,9 +12,9 @@
 struct SimoleonApp: App {
     let persistenceController = PersistenceController.shared
     init() {
-            Purchases.configure(withAPIKey: "\(readConfig("PURCHASES_KEY")!)")
-        }
-
+        Purchases.configure(withAPIKey: "\(readConfig("PURCHASES_KEY")!)")
+    }
+    
     var body: some Scene {
         WindowGroup {
             if UIDevice.current.userInterfaceIdiom == .pad {
--- a/Simoleon/SubscriptionPaywall.swift	Mon Jul 26 18:25:03 2021 +0100
+++ b/Simoleon/SubscriptionPaywall.swift	Mon Jul 26 20:08:20 2021 +0100
@@ -73,7 +73,7 @@
                                 Link(destination: URL(string: "https://dennistech.io/privacy-policy")!) {
                                     Text("Privacy Policy", comment: "Button to go to app privacy policy")
                                 }
-
+                                
                                 Link(destination: URL(string: "https://dennistech.io/terms-of-use")!) {
                                     Text("Terms of Use", comment: "Button to go to app terms of use")
                                 }