Swift closure capture array by reference -


in swift collections pass value default , can user inout make pass reference in function arguments how can in closure capture variables?

var list = [1, 2, 3] func edit(inout list: [int]) {     list.append(4)     dispatch_async(dispatch_get_main_queue()) {         list.append(5)     } } edit(&list) ...// after dispatch_async executed  nslog("\(list)") 

result [1, 2, 3, 4]

how can modify original variable () inside closure?

update:

actually have workaround handle case putting array object can pass object function reference , can modify same array instance inside function. want see clever way archive that

for getting variable escape closure need @escaping, check this out. workaround put completion function argument rather inout variable.

class myclass {     static func edit(_ list: [int], _ completion: @escaping ([int]) -> ()) {         var list = list         list.append(4)         dispatchqueue.main.async() {             list.append(5)             completion(list)         }     } }  var mylist = [1, 2, 3] myclass.edit(mylist) { (list) in     mylist = list     print("my list after editing: \(mylist)") } print("my list without editing: \(mylist)") 

note: above example swift 3 inout parameters not allowed captured in closures. based on post, may using lower version of swift might able use inout rather setting mutable copy of list: var list = list. however, logic similar.

for more information, check limiting inout capture @noescape contexts in swift evolution:

swift's behavior when closures capture inout parameters , escape enclosing context common source of confusion. should disallow implicit capture of inout parameters except in @noescape closures.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -