-1

I spent lot of time to fix this issue with other solutions unable to make it work.

public struct LoanDetails {
    public var dueDate: String?
    
    public init() {}
}

public func getLoanDetails(_ result: @escaping (_ loanDetails: LoanDetails?, _ error: Error?) -> Void) {
//This is an API call it returns data here mentioned to get current date.
        var loanDetails = LoanDetails()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMMM d, yyyy"
        loanDetails.dueDate =  dateFormatter.string(from: Date())
        result(loanDetails, nil)
    }

When I'm calling this getLoanDetails function in viewModel it throws an error: escaping closure captures mutating 'self' parameter

struct MyViewModel {
    var var dueDate: String?
    
    mutating func getLoanData() { //must be mutating to set some other properties
        getLoanDetails({ (loanDetails, error) in
            dueDate = loanDetails?.dueDate // Getting error here
        })
    }
}

Calling getLoanData() from viewDidload can anyone suggest correct way of doing this.

I know by changing viewModel struct to class and removing mutating keyword it works but I wanted to maintain all viewModels as struct in app.

iOSDuDe
  • 35
  • 5

2 Answers2

0

You can achieve with by changing MyViewModel struct to class will solve your problem.

class MyViewModel {
   var dueDate: String?
        
   func getLoanData() {
        getLoanDetails { loanDetails, error in
        self.dueDate = loanDetails?.dueDate
      }
   }
}
Mitesh Mistri
  • 439
  • 2
  • 8
  • With struct can we able to make it to fixable? can you suggest is there any way I've to keep this as struct only . – iOSDuDe Jan 13 '22 at 12:45
  • I need to maintain all view models as struct only can it be possible in this case? – iOSDuDe Jan 13 '22 at 13:18
  • I think no. Check this link - https://stackoverflow.com/questions/39702990/mutating-self-struct-enum-inside-escaping-closure-in-swift-3-0. – Levan Karanadze Jan 13 '22 at 13:54
-1

Just add self prefix before dueDate. It will be like this

struct MyViewModel {
        var dueDate: String?
        mutating func getLoanData() { //must be mutating to set some other
           getLoanDetails({ (loanDetails, error) in
           self.dueDate = loanDetails?.dueDate // Getting error here
           })
        }
}     
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 14 '22 at 00:33