美文网首页iOS
架构之路 (八) —— iOS App的SOLID原则(二)

架构之路 (八) —— iOS App的SOLID原则(二)

作者: 刀客传奇 | 来源:发表于2021-07-04 18:46 被阅读0次

    版本记录

    版本号 时间
    V1.0 2020.07.04 星期日

    前言

    前面写了那么多篇主要着眼于局部问题的解决,包括特定功能的实现、通用工具类的封装、视频和语音多媒体的底层和实现以及动画酷炫的实现方式等等。接下来这几篇我们就一起看一下关于iOS系统架构以及独立做一个APP的架构设计的相关问题。感兴趣的可以看上面几篇。
    1. 架构之路 (一) —— iOS原生系统架构(一)
    2. 架构之路 (二) —— APP架构分析(一)
    3. 架构之路 (三) —— APP架构之网络层分析(一)
    4. 架构之路 (四) —— APP架构之工程实践中网络层的搭建(二)
    5. 架构之路 (五) —— VIPER架构模式(一)
    6. 架构之路 (六) —— VIPER架构模式(二)
    7. 架构之路 (七) —— iOS App的SOLID原则(一)

    源码

    1. Swift

    修改之前

    首先看下工程组织结构

    下面就是源码了

    1. Date.swift
    
    import Foundation
    
    extension Date {
      var startOfDay: Date {
        return Calendar.current.startOfDay(for: self)
      }
    
      var startOfMonth: Date {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.year, .month], from: self)
    
        return calendar.date(from: components) ?? Date()
      }
    
      var startOfWeek: Date {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
    
        return calendar.date(from: components) ?? Date()
      }
    
      var endOfDay: Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startOfDay) ?? Date()
      }
    
      var endOfMonth: Date {
        var components = DateComponents()
        components.month = 1
        components.second = -1
        return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth) ?? Date()
      }
    
      var endOfWeek: Date {
        var components = DateComponents()
        components.weekOfYear = 1
        components.second = -1
        return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfWeek) ?? Date()
      }
    }
    
    2. ExpenseModel+CoreDataClass.swift
    
    import Foundation
    import CoreData
    
    @objc(ExpenseModel)
    public class ExpenseModel: NSManagedObject {
    }
    
    3. ExpenseModel+CoreDataProperties.swift
    
    import Foundation
    import CoreData
    
    
    extension ExpenseModel {
      @nonobjc
      public class func fetchRequest() -> NSFetchRequest<ExpenseModel> {
        return NSFetchRequest<ExpenseModel>(entityName: "ExpenseModel")
      }
    
      @NSManaged public var title: String?
      @NSManaged public var price: Double
      @NSManaged public var comment: String?
      @NSManaged public var date: Date?
      @NSManaged public var id: UUID?
    }
    
    extension ExpenseModel: Identifiable {
    }
    
    4. DailyReportsDataSource.swift
    
    import CoreData
    import Combine
    
    class DailyReportsDataSource: ObservableObject {
      var viewContext: NSManagedObjectContext
    
      @Published private(set) var currentEntries: [ExpenseModel] = []
    
      init(viewContext: NSManagedObjectContext = AppMain.container.viewContext) {
        self.viewContext = viewContext
        prepare()
      }
    
      func prepare() {
        currentEntries = getEntries()
      }
    
      private func getEntries() -> [ExpenseModel] {
        let fetchRequest: NSFetchRequest<ExpenseModel> = ExpenseModel.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \ExpenseModel.date, ascending: false)]
        fetchRequest.predicate = NSPredicate(
          format: "%@ <= date AND date <= %@",
          Date().startOfDay as CVarArg,
          Date().endOfDay as CVarArg)
        do {
          let results = try viewContext.fetch(fetchRequest)
          return results
        } catch let error {
          print(error)
          return []
        }
      }
    
      func saveEntry(title: String, price: Double, date: Date, comment: String) {
        let newItem = ExpenseModel(context: viewContext)
        newItem.title = title
        newItem.date = date
        newItem.comment = comment
        newItem.price = price
        newItem.id = UUID()
    
        if let index = currentEntries.firstIndex(where: { $0.date ?? Date() < date }) {
          currentEntries.insert(newItem, at: index)
        } else {
          currentEntries.append(newItem)
        }
    
        try? viewContext.save()
      }
    
      func delete(entry: ExpenseModel) {
        viewContext.delete(entry)
        try? viewContext.save()
      }
    }
    
    5. MonthlyReportsDataSource.swift
    
    import CoreData
    import Combine
    
    class MonthlyReportsDataSource: ObservableObject {
      var viewContext: NSManagedObjectContext
    
      @Published private(set) var currentEntries: [ExpenseModel] = []
    
      init(viewContext: NSManagedObjectContext = AppMain.container.viewContext) {
        self.viewContext = viewContext
        prepare()
      }
    
      func prepare() {
        currentEntries = getEntries()
      }
    
      private func getEntries() -> [ExpenseModel] {
        let fetchRequest: NSFetchRequest<ExpenseModel> = ExpenseModel.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \ExpenseModel.date, ascending: false)]
        fetchRequest.predicate = NSPredicate(
          format: "%@ <= date AND date <= %@",
          Date().startOfMonth as CVarArg,
          Date().endOfMonth as CVarArg)
        do {
          let results = try viewContext.fetch(fetchRequest)
          return results
        } catch let error {
          print(error)
          return []
        }
      }
    
      func saveEntry(title: String, price: Double, date: Date, comment: String) {
        let newItem = ExpenseModel(context: viewContext)
        newItem.title = title
        newItem.date = date
        newItem.comment = comment
        newItem.price = price
        newItem.id = UUID()
    
        if let index = currentEntries.firstIndex(where: { $0.date ?? Date() < date }) {
          currentEntries.insert(newItem, at: index)
        } else {
          currentEntries.append(newItem)
        }
    
        try? viewContext.save()
      }
    
      func delete(entry: ExpenseModel) {
        viewContext.delete(entry)
        try? viewContext.save()
      }
    }
    
    6. ContentView.swift
    
    import SwiftUI
    
    struct ContentView: View {
      var body: some View {
        NavigationView {
          List {
            NavigationLink(
              "Today",
              destination: dailyReport
                .navigationTitle("Today"))
            NavigationLink(
              "This Month",
              destination: monthlyReport
                .navigationTitle("This Month"))
          }
          .navigationTitle("Reports")
        }
      }
    
      var dailyReport: DailyExpensesView {
        let dailyDataSource = DailyReportsDataSource()
        return DailyExpensesView(dataSource: dailyDataSource)
      }
    
      var monthlyReport: MonthlyExpensesView {
        let monthlyDataSource = MonthlyReportsDataSource()
        return MonthlyExpensesView(dataSource: monthlyDataSource)
      }
    }
    
    struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
        ContentView()
      }
    }
    
    7. DailyExpensesView.swift
    
    import SwiftUI
    import Combine
    
    struct DailyExpensesView: View {
      @State private var isAddPresented = false
      @ObservedObject var dataSource: DailyReportsDataSource
    
      var body: some View {
        VStack {
          List {
            ForEach(dataSource.currentEntries, id: \.id) { item in
              ExpenseItemView(expenseItem: item)
            }
          }
          TotalView(totalExpense: dataSource.currentEntries.reduce(0) { $0 + $1.price })
        }
        .toolbar {
          Button(action: {
            isAddPresented.toggle()
          }, label: {
            Image(systemName: "plus")
          })
        }
        .fullScreenCover(
          isPresented: $isAddPresented) {
          AddExpenseView { title, price, time, comment in
            dataSource.saveEntry(title: title, price: price, date: time, comment: comment)
          }
        }
        .onAppear {
          dataSource.prepare()
        }
      }
    }
    
    struct DailyExpensesView_Previews: PreviewProvider {
      static var previews: some View {
        let reportsDataSource = DailyReportsDataSource(viewContext: AppMain.previewContainer.viewContext)
        DailyExpensesView(dataSource: reportsDataSource)
      }
    }
    
    8. MonthlyExpensesView.swift
    
    import SwiftUI
    import Combine
    
    struct MonthlyExpensesView: View {
      @State private var isAddPresented = false
      @ObservedObject var dataSource: MonthlyReportsDataSource
    
      var body: some View {
        VStack {
          List {
            ForEach(dataSource.currentEntries, id: \.id) { item in
              ExpenseItemView(expenseItem: item)
            }
          }
          TotalView(totalExpense: dataSource.currentEntries.reduce(0) { $0 + $1.price })
        }
        .toolbar {
          Button(action: {
            isAddPresented.toggle()
          }, label: {
            Image(systemName: "plus")
          })
        }
        .fullScreenCover(
          isPresented: $isAddPresented) {
          AddExpenseView { title, price, time, comment in
            dataSource.saveEntry(title: title, price: price, date: time, comment: comment)
          }
        }
        .onAppear {
          dataSource.prepare()
        }
      }
    }
    
    struct MonthlyExpensesView_Previews: PreviewProvider {
      static var previews: some View {
        let reportsDataSource = MonthlyReportsDataSource(viewContext: AppMain.previewContainer.viewContext)
        MonthlyExpensesView(dataSource: reportsDataSource)
      }
    }
    
    9. AddExpenseView.swift
    
    import SwiftUI
    
    struct AddExpenseView: View {
      @Environment(\.presentationMode) var presentation
      var saveClosure: (String, Double, Date, String) -> Void
    
      @State var title: String = ""
      @State var time = Date()
      @State var comment: String = ""
      @State var price: String = ""
      @State var saveDisabled = true
      var body: some View {
        NavigationView {
          VStack(alignment: .leading) {
            Text("Title:")
            TextField("Entry Title", text: $title)
              .onChange(of: title) { _ in
                validateNonEmptyFields()
              }
              .padding(.bottom)
            Text("Amount:")
            TextField("Expense Amount", text: $price)
              .keyboardType(.numberPad)
              .onChange(of: price) { _ in
                validateNonEmptyFields()
              }
              .padding(.bottom)
            DatePicker(
              "Time:",
              selection: $time,
              displayedComponents: [.hourAndMinute])
              .padding(.bottom)
            Text("Comment:")
            TextEditor(text: $comment)
          }
          .padding(.all)
          .navigationBarTitle("Add Expense", displayMode: .inline)
          .navigationBarItems(
            leading: Button(action: cancelEntry) {
              Text("Cancel")
            },
            trailing: Button(action: saveEntry) {
              Text("Save")
            }.disabled(saveDisabled))
        }
      }
    
      func saveEntry() {
        guard let numericPrice = Double(price), numericPrice > 0 else {
          return
        }
    
        saveClosure(title, numericPrice, time, comment)
        cancelEntry()
      }
    
      func cancelEntry() {
        presentation.wrappedValue.dismiss()
      }
    
      func validateNonEmptyFields() {
        guard Double(price) != nil else {
          saveDisabled = true
          return
        }
        saveDisabled = title.isEmpty
      }
    }
    
    struct AddExpenseView_Previews: PreviewProvider {
      static var previews: some View {
        AddExpenseView { _, _, _, _ in
        }
      }
    }
    
    10. ExpenseItemView.swift
    
    import SwiftUI
    
    struct ExpenseItemView: View {
      let expenseItem: ExpenseModel
    
      static let dateFormatter: DateFormatter = {
        var dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .none
        return dateFormatter
      }()
    
      static let timeFormatter: DateFormatter = {
        var dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .none
        dateFormatter.timeStyle = .medium
        return dateFormatter
      }()
    
      var body: some View {
        VStack(alignment: .leading) {
          HStack {
            Text(expenseItem.title ?? "")
            Spacer()
            Text(String(format: "%.2f", expenseItem.price))
          }
          Text(expenseItem.comment ?? "")
            .font(.caption)
          HStack {
            Text("\(expenseItem.date ?? Date(), formatter: Self.dateFormatter)")
            Spacer()
            Text("\(expenseItem.date ?? Date(), formatter: Self.timeFormatter)")
          }
        }
      }
    }
    
    struct ExpenseItemView_Previews: PreviewProvider {
      static var previews: some View {
        ExpenseItemView(expenseItem: AppMain.previewItem)
      }
    }
    
    11. TotalView.swift
    
    import SwiftUI
    
    struct TotalView: View {
      var totalExpense: Double = 0
      var body: some View {
        HStack {
          Text("Total")
          Spacer()
          Text(String(format: "%.2f", totalExpense))
            .font(.title)
        }
        .padding(.horizontal)
      }
    }
    
    struct TotalView_Previews: PreviewProvider {
      static var previews: some View {
        TotalView(totalExpense: 123.45)
      }
    }
    
    12. AppMain.swift
    
    import SwiftUI
    import CoreData
    
    @main
    struct AppMain: App {
      static var container: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "ExpensesModel")
        container.loadPersistentStores { _, error in
          if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        }
        return container
      }()
    
      static var previewContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "ExpensesModel")
        container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        container.loadPersistentStores { _, error in
          if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        }
    
        for index in 0..<5 {
          let newItem = ExpenseModel(context: container.viewContext)
          newItem.title = "Test Title \(index)"
          newItem.date = Date(timeIntervalSinceNow: Double(index * 60))
          newItem.comment = "Test Comment \(index)"
          newItem.price = Double(index + 1) * 12.3
          newItem.id = UUID()
        }
        do {
          try container.viewContext.save()
        } catch {
          let nsError = error as NSError
          fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    
        return container
      }()
    
      static let previewItem: ExpenseModel = {
        let newItem = ExpenseModel(context: AppMain.previewContainer.viewContext)
        newItem.title = "Preview Item Title"
        newItem.date = Date(timeIntervalSinceNow: 60)
        newItem.comment = "Preview Item Comment"
        newItem.price = 12.34
        newItem.id = UUID()
        return newItem
      }()
    
      var body: some Scene {
        WindowGroup {
          ContentView()
        }
      }
    }
    

    修改之后

    首先看下工程组织结构

    下面就是源码了

    1. ReportReader.swift
    
    import Foundation
    
    class ReportReader: ObservableObject {
      @Published var currentEntries: [ExpenseModelProtocol] = []
    
      func prepare() {
        assertionFailure("Missing override: Please override this method in the subclass")
      }
    }
    
    2. ExpenseModelProtocol.swift
    
    import Foundation
    
    protocol ExpenseModelProtocol {
      var title: String? { get }
      var price: Double { get }
      var comment: String? { get }
      var date: Date? { get }
      var id: UUID? { get }
    }
    
    3. SaveEntryProtocol.swift
    
    import Foundation
    
    protocol SaveEntryProtocol {
      func saveEntry(
        title: String,
        price: Double,
        date: Date,
        comment: String
      ) -> Bool
    }
    
    4. ReportRange.swift
    
    import Foundation
    
    enum ReportRange: String, CaseIterable {
      case daily = "Today"
      case monthly = "This Month"
      case weekly = "This Week"
    
      func timeRange() -> (Date, Date) {
        let now = Date()
        switch self {
        case .daily:
          return (now.startOfDay, now.endOfDay)
        case .monthly:
          return (now.startOfMonth, now.endOfMonth)
        case .weekly:
          return (now.startOfWeek, now.endOfWeek)
        }
      }
    }
    
    5. Date.swift
    
    import Foundation
    
    extension Date {
      var startOfDay: Date {
        return Calendar.current.startOfDay(for: self)
      }
    
      var startOfMonth: Date {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.year, .month], from: self)
    
        return calendar.date(from: components) ?? Date()
      }
    
      var startOfWeek: Date {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
    
        return calendar.date(from: components) ?? Date()
      }
    
      var endOfDay: Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startOfDay) ?? Date()
      }
    
      var endOfMonth: Date {
        var components = DateComponents()
        components.month = 1
        components.second = -1
        return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth) ?? Date()
      }
    
      var endOfWeek: Date {
        var components = DateComponents()
        components.weekOfYear = 1
        components.second = -1
        return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfWeek) ?? Date()
      }
    }
    
    6. ExpenseModel+CoreDataClass.swift
    
    import Foundation
    import CoreData
    
    @objc(ExpenseModel)
    public class ExpenseModel: NSManagedObject {
    }
    
    7. ExpenseModel+CoreDataProperties.swift
    
    import Foundation
    import CoreData
    
    
    extension ExpenseModel {
      @nonobjc
      public class func fetchRequest() -> NSFetchRequest<ExpenseModel> {
        return NSFetchRequest<ExpenseModel>(entityName: "ExpenseModel")
      }
    
      @NSManaged public var title: String?
      @NSManaged public var price: Double
      @NSManaged public var comment: String?
      @NSManaged public var date: Date?
      @NSManaged public var id: UUID?
    }
    
    extension ExpenseModel: Identifiable {
    }
    
    8. ReportsDataSource.swift
    
    import CoreData
    import Combine
    
    class ReportsDataSource: ReportReader, SaveEntryProtocol {
      let reportRange: ReportRange
    
      init(
        viewContext: NSManagedObjectContext = PersistenceController.shared.container.viewContext,
        reportRange: ReportRange
      ) {
        self.viewContext = viewContext
        self.reportRange = reportRange
        super.init()
        currentEntries = getEntries()
      }
    
      override func prepare() {
        currentEntries = getEntries()
      }
    
      var viewContext: NSManagedObjectContext
    
      private func getEntries() -> [ExpenseModelProtocol] {
        let fetchRequest: NSFetchRequest<ExpenseModel> =
          ExpenseModel.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \ExpenseModel.date, ascending: false)]
        let (startDate, endDate) = reportRange.timeRange()
        fetchRequest.predicate = NSPredicate(
          format: "%@ <= date AND date <= %@",
          startDate as CVarArg,
          endDate as CVarArg)
        do {
          let results = try viewContext.fetch(fetchRequest)
          return results
        } catch let error {
          print(error)
          return []
        }
      }
    
      func saveEntry(title: String, price: Double, date: Date, comment: String) -> Bool {
        let newItem = ExpenseModel(context: viewContext)
        newItem.title = title
        newItem.date = date
        newItem.comment = comment
        newItem.price = price
        newItem.id = UUID()
    
        if let index = currentEntries.firstIndex(where: { $0.date ?? Date() < date }) {
          currentEntries.insert(newItem, at: index)
        } else {
          currentEntries.append(newItem)
        }
    
        try? viewContext.save()
        return true
      }
    
      func delete(entry: ExpenseModel) {
        viewContext.delete(entry)
        try? viewContext.save()
      }
    }
    
    9. Persistence.swift
    
    import Foundation
    import CoreData
    
    struct PersistenceController {
      static let shared = PersistenceController()
    
      let container: NSPersistentContainer
    
      init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "ExpensesModel")
        if inMemory {
          container.persistentStoreDescriptions.first?.url = URL(
            fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores { _, error in
          if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        }
      }
    }
    
    10. ExpenseModel+Protocol.swift
    
    import Foundation
    
    extension ExpenseModel: ExpenseModelProtocol { }
    
    11. ContentView.swift
    
    import SwiftUI
    
    struct ContentView: View {
      var body: some View {
        NavigationView {
          List {
            ForEach(ReportRange.allCases, id: \.self) { value in
              NavigationLink(
                value.rawValue,
                destination: expenseView(for: value)
                  .navigationTitle(value.rawValue))
            }
          }
          .navigationTitle("Reports")
        }
      }
    
      func expenseView(for range: ReportRange) -> ExpensesView {
        let dataSource = ReportsDataSource(reportRange: range)
        return ExpensesView(dataSource: dataSource)
      }
    }
    
    struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
        ContentView()
      }
    }
    
    12. ExpensesView.swift
    
    import SwiftUI
    import Combine
    
    struct ExpensesView: View {
      @State private var isAddPresented = false
      @ObservedObject var dataSource: ReportReader
    
      var body: some View {
        VStack {
          List {
            ForEach(dataSource.currentEntries, id: \.id) { item in
              ExpenseItemView(expenseItem: item)
            }
          }
          TotalView(totalExpense: dataSource.currentEntries.reduce(0) { $0 + $1.price })
        }
        .toolbar {
          Button(action: {
            isAddPresented.toggle()
          }, label: {
            Image(systemName: "plus")
          })
        }
        .fullScreenCover(isPresented: $isAddPresented) { () -> AddExpenseView? in
          guard let saveHandler = dataSource as? SaveEntryProtocol else {
            return nil
          }
          return AddExpenseView(saveEntryHandler: saveHandler)
        }
        .onAppear {
          dataSource.prepare()
        }
      }
    }
    
    struct ExpensesView_Previews: PreviewProvider {
      struct PreviewExpenseEntry: ExpenseModelProtocol {
        var title: String?
        var price: Double
        var comment: String?
        var date: Date?
        var id: UUID? = UUID()
      }
    
      class PreviewReportsDataSource: ReportReader, SaveEntryProtocol {
        override init() {
          super.init()
          for index in 1..<6 {
            _ = saveEntry(
              title: "Test Title \(index)",
              price: Double(index) * 12.3,
              date: Date(timeIntervalSinceNow: Double(index * -60)),
              comment: "Test Comment \(index)")
          }
        }
    
        override func prepare() {
        }
    
        func saveEntry(
          title: String,
          price: Double,
          date: Date,
          comment: String
        ) -> Bool {
          let newEntry = PreviewExpenseEntry(
            title: title,
            price: price,
            comment: comment,
            date: date)
          currentEntries.append(newEntry)
          return true
        }
      }
    
      static var previews: some View {
        ExpensesView(dataSource: PreviewReportsDataSource())
      }
    }
    
    13. AddExpenseView.swift
    
    import SwiftUI
    
    struct AddExpenseView: View {
      @Environment(\.presentationMode) var presentation
      var saveEntryHandler: SaveEntryProtocol
    
      @State var title: String = ""
      @State var time = Date()
      @State var comment: String = ""
      @State var price: String = ""
      @State var saveDisabled = true
    
      var body: some View {
        NavigationView {
          VStack(alignment: .leading) {
            Text("Title:")
            TextField("Entry Title", text: $title)
              .onChange(of: title) { _ in
                validateNonEmptyFields()
              }
              .padding(.bottom)
            Text("Amount:")
            TextField("Expense Amount", text: $price)
              .keyboardType(.numberPad)
              .onChange(of: price) { _ in
                validateNonEmptyFields()
              }
              .padding(.bottom)
            DatePicker(
              "Time:",
              selection: $time,
              displayedComponents: [.hourAndMinute])
              .padding(.bottom)
            Text("Comment:")
            TextEditor(text: $comment)
          }
          .padding(.all)
          .navigationBarTitle("Add Expense", displayMode: .inline)
          .navigationBarItems(
            leading: Button(action: cancelEntry) {
              Text("Cancel")
            },
            trailing: Button(action: saveEntry) {
              Text("Save")
            }
            .disabled(saveDisabled))
        }
      }
    
      func saveEntry() {
        guard let numericPrice = Double(price), numericPrice > 0 else {
          return
        }
    
        guard saveEntryHandler.saveEntry(
          title: title,
          price: numericPrice,
          date: time,
          comment: comment)
        else {
          print("Invalid entry.")
          return
        }
    
        cancelEntry()
      }
    
      func cancelEntry() {
        presentation.wrappedValue.dismiss()
      }
    
      func validateNonEmptyFields() {
        guard Double(price) != nil else {
          saveDisabled = true
          return
        }
        saveDisabled = title.isEmpty
      }
    }
    
    struct AddExpenseView_Previews: PreviewProvider {
      class PreviewSaveHandler: SaveEntryProtocol {
        func saveEntry(title: String, price: Double, date: Date, comment: String) -> Bool {
          return true
        }
      }
      static var previews: some View {
        AddExpenseView(saveEntryHandler: PreviewSaveHandler())
      }
    }
    
    14. ExpenseItemView.swift
    
    import SwiftUI
    
    struct ExpenseItemView: View {
      let expenseItem: ExpenseModelProtocol
    
      static let dateFormatter: DateFormatter = {
        var dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .none
        return dateFormatter
      }()
    
      static let timeFormatter: DateFormatter = {
        var dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .none
        dateFormatter.timeStyle = .medium
        return dateFormatter
      }()
    
      var body: some View {
        VStack(alignment: .leading) {
          HStack {
            Text(expenseItem.title ?? "")
            Spacer()
            Text(String(format: "%.2f", expenseItem.price))
          }
          Text(expenseItem.comment ?? "")
            .font(.caption)
          HStack {
            Text("\(expenseItem.date ?? Date(), formatter: Self.dateFormatter)")
            Spacer()
            Text("\(expenseItem.date ?? Date(), formatter: Self.timeFormatter)")
          }
        }
      }
    }
    
    struct ExpenseItemView_Previews: PreviewProvider {
      struct PreviewExpenseModel: ExpenseModelProtocol {
        var title: String? = "Preview Item"
        var price: Double = 123.45
        var comment: String? = "This is a preview item"
        var date: Date? = Date()
        var id: UUID? = UUID()
      }
    
      static var previews: some View {
        ExpenseItemView(expenseItem: PreviewExpenseModel())
      }
    }
    
    15. TotalView.swift
    
    import SwiftUI
    
    struct TotalView: View {
      var totalExpense: Double = 0
      var body: some View {
        HStack {
          Text("Total")
          Spacer()
          Text(String(format: "%.2f", totalExpense))
            .font(.title)
        }
        .padding(.horizontal)
      }
    }
    
    struct TotalView_Previews: PreviewProvider {
      static var previews: some View {
        TotalView(totalExpense: 123.45)
      }
    }
    
    16. AppMain.swift
    
    import SwiftUI
    import CoreData
    
    @main
    struct AppMain: App {
      static var container: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "ExpensesModel")
        container.loadPersistentStores { _, error in
          if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        }
        return container
      }()
    
      static var previewContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "ExpensesModel")
        container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        container.loadPersistentStores { _, error in
          if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
          }
        }
    
        for index in 0..<5 {
          let newItem = ExpenseModel(context: container.viewContext)
          newItem.title = "Test Title \(index)"
          newItem.date = Date(timeIntervalSinceNow: Double(index * 60))
          newItem.comment = "Test Comment \(index)"
          newItem.price = Double(index + 1) * 12.3
          newItem.id = UUID()
        }
        do {
          try container.viewContext.save()
        } catch {
          let nsError = error as NSError
          fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    
        return container
      }()
    
      static let previewItem: ExpenseModel = {
        let newItem = ExpenseModel(context: AppMain.previewContainer.viewContext)
        newItem.title = "Preview Item Title"
        newItem.date = Date(timeIntervalSinceNow: 60)
        newItem.comment = "Preview Item Comment"
        newItem.price = 12.34
        newItem.id = UUID()
        return newItem
      }()
    
      var body: some Scene {
        WindowGroup {
          ContentView()
        }
      }
    }
    

    后记

    本篇主要讲述了iOS AppSOLID原则,感兴趣的给个赞或者关注~~~

    相关文章

      网友评论

        本文标题:架构之路 (八) —— iOS App的SOLID原则(二)

        本文链接:https://www.haomeiwen.com/subject/kdcvultx.html