1

I'm trying to define a class including a closure to update its variables. The class definition looks like:

class Layout
{
    let name: String
    var  choHash: [String: String]
    var jungHash: [String: String]
    var jongHash: [String: String]
    let updater: ([String: String], [String: String], [String: String] -> ())

    init(name: String, choHash: [String: String], jungHash: [String: String], jongHash: [String: String], updater: ([String: String], [String: String], [String: String] -> ()))
    {
        self.name = name
        self.choHash  =  choHash
        self.jungHash = jungHash
        self.jongHash = jongHash
        self.updater = updater
    }

    func update() -> ()
    {
        self.updater(self.choHash, self.jungHash, self.jongHash) // Error here
    }
}

So this is pretty much like what I'd do in Ruby, for example. However, XCode shows an error here:

'(@lvalue [String : String], @lvalue [String : String], @lvalue [String : String]) -> $T8' is not identical to '([String : String], [String : String], [String : String] -> ())'

I have two questions:

  1. Why does this happen, and how can I address the problem? Especially, why does it comprehends the statement as passing the @lvalue [String: String], instead of [String: String]?

  2. Once the problem is solved, will the variables choHash, jungHash and jongHash updated properly?

1 Answer 1

0

The problem is that this type:

([String: String], [String: String], [String: String] -> ())

is not a function type.

It’s a 3-tuple containing two dictionaries and a function from dictionary to void.

If you want a function that takes 3 dictionaries, this is the type you need:

([String: String], [String: String], [String: String]) -> ()

If you amend the type in the let and in the init argument, it compiles OK.

That said, when you say:

will the variables choHash, jungHash and jongHash updated properly?

The answer is – probably not. Are you expecting, when you call x.update, for the dictionaries in x to be updated by the closure? If so, they won’t be (unless that closure somehow can get a reference back to x itself). Dictionaries in Swift are passed by value, so unless they are passed as an inout parameter nothing the called function can do will alter the values the caller passed in.

1
  • Oh, what a silly mistake. Adding "inout"s, now this code runs flawlessly. Thank you. Mar 17, 2015 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.