简体   繁体   中英

Inout parameter in closure (Swift)

I would like to call a method which have an inout parameter. And in this method there is a closure. Here is what I did:

var groups : [Group]
func setup() {
    ... // add some element to the array...

    self.setupUser(user, group: &groups!)
    ...
}

func setupUser(user: User, inout group: [Group]) {
    user.getGroup(callBack: ({(aGroup:Group) in
        group[0] = aGroup
    }))
}

But after I called the setupUser method, the first element of the array [0] didn't changed. I think the problem is that I use an inout parameter in a closure, but how to fix this problem in Swift?

Try group.append(aGroup) . That worked for me.

Playground:

import Cocoa
struct Group {
  var name:String
}
class User {
  var name:String
  init() {
    name = ""
  }

  func setupUser(user:User, group:[Group]) {

  }

  func getGroup (callBack: (Group) -> ()) {
    println("call")
    callBack(Group(name: "Test"))
    println("back")
  }
}
var groups =  [Group]()
var user = User()
func setup() {

  setupUser(user, &groups)
}

func setupUser(user: User, inout group: [Group]) {
  println("hi")
  user.getGroup(({(aGroup:Group) in
    println(group)
    println(aGroup)
    group.append(aGroup)
  }))
}

setup()
groups

The inout variable should be assignable within the closure:

struct Group {
    let value: Int
}

struct User {
    func getGroup(callback: Group->()) {
        callback(Group(value: 2))
    }
}

var groups: [Group] = [Group(value: 1)]
func setup() {
    setupUser(User(), &groups)
}

func setupUser(user: User, inout group: [Group]) {
    user.getGroup  { aGroup in
        // assigns to the inout variable
        group[0] = aGroup
    }
}

groups[0] // a Group with value = 1
setup()
groups[0] // now a Group with value = 2

I think your actual problem might lie in a part of the code you didn't include in your post since what you posted won't work as-is (for example, in your actual code is groups really just an array? Or is it an optional containing an array, since otherwise it wouldn't need a ! to force-unwrap it...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM