Angelo Angelo - 4 years ago 117
Swift Question

Variable assignment failure in Swift

I have a Swift class

Test
with the following initializer.

import Foundation

class Test {
var x: Int

var response: [String: AnyObject]

init(_ x: Int) {
self.x = x

self.response = [String: AnyObject]()

self.y(x)
}
}


Inside
Test
, I also have the following method.

func y(_ x: Int) {
// This is a task with a completion handler of type (_, _, _) -> Void
let ... = ...(with: ..., completionHandler: { () in
do {
// The type of z is [String: AnyObject]
let z = ...
self.response = z
} catch {
return
}
})


Calling
y
is supposed to reassign
z
to
self.response
, but
self.response
is persistently an empty dictionary.

Am I missing something?

Answer Source

Although this way seems like something you might want to reconsider (and I am going to point you to this nice answer on a similar question: http://stackoverflow.com/a/12797624/2617369), the way I would do it with a combo of adding a completion to your y method and with a dispatch group like this:

(This is swift 3 because I don't have a previous version IDE to show you in 2.3 but it should not be much different):

class Test {
    var x: Int

var response: [String: Any]

init(_ x: Int) {
    self.x = x

    self.response = [String: Any]()

    let group = DispatchGroup()
    group.enter()
    self.y(x) { (result) in
        self.response = result
        group.leave()
    }

    group.wait()
}

func y(_ x: Int, completion:@escaping (([String:Any])->())) {
    // This is a task with a completion handler of type (_, _, _) -> Void
    let ... = ...(with: ..., completionHandler: { () in
        do {
        // The type of z is [String: Any]
            let z = ...
            completion(z);
        } catch {
        return
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download