The concept of capture variables is very not obvious for me, especially when variables is of value types. I have a simple model of client side server. It has the abstract connection and server structures. Server stores the useful data and handles Responses and updates the model inside Apps structures. The AppTwo works, and AppOne does not work with the next short error: Escaping closure captures mutating 'self' parameter
The code:
struct Response {}
struct Request {}
struct Connection {
var listener: ((Response) -> Void)?
func listen() { listener?(Response()) }
func send(request: Request) {}
}
struct Server {
var usefulSroredData: Int = 0
func serve(response: Response, connection: Connection, handler: @escaping ([Int]) -> Void ) {
connection.send(request: Request()) // Some times it would send any data to the connection
handler([3, 2, 1])
}
}
struct AppOne {
var model: [Int]
var server: Server
init() {
model = [1, 2, 3]
server = Server()
}
mutating func run() {
var connection = Connection()
func handleResponse(response: Response) {
server.serve(response: response, connection: connection) { newmodel in self.model = newmodel } // Escaping closure captures mutating 'self' parameter
}
connection.listener = handleResponse //Escaping closure captures mutating 'self' parameter
connection.listen()
}
}
struct AppTwo {
func run() {
var model: [Int] = [1, 2, 3]
var server: Server = Server()
var connection = Connection()
func handleResponse(response: Response) {
server.serve(response: response, connection: connection) { newmodel in model = newmodel }
}
connection.listener = handleResponse
connection.listen()
}
}
The question is: it is almost same App's model. Why compeller does not allow me modify properties of the structure, but allow modify variables within functions?