Reputation: 659
I'm having issues with initialization of a custom class. I need to set up an observer on some data when the class is initialized which updates properties. Initially, the properties can be empty and that is how I set them at initiation. However, Xcode still throws the "'self' captured by a closure before all members were initialized" error. Here is a shortened version of the code.
class Foo {
init() {
self.usersRef = ref.child("users")
self.usersRef.observe(DataEventType.value, with: { (snapshot) in
// snapshot error checking
// users is [String]
self.users = users
})
}
private var usersRef: DatabaseReference
private(set) var users: [String] = []
}
I have also tried
class Foo {
init() {
self.users = [String]()
self.usersRef = ref.child("users")
self.usersRef.observe(DataEventType.value, with: { (snapshot) in
// snapshot error checking
// users is [String]
self.users = users
})
}
private var usersRef: DatabaseReference
private(set) var users: [String]
}
to ensure initialization prior to the callback.
From this question it seemed I only needed to give the properties initial values, but this does not seem to be the case. I would prefer not to have to call another function to set up these handlers after initialization.
Thank you for an help
Upvotes: 4
Views: 3366
Reputation: 27211
Try to use this block
{ [unowned self] (snapshot) in
// snapshot error checking
// users is [String]
self.users = users
})
or
{ [weak self] (snapshot) in
// snapshot error checking
// users is [String]
self?.users = users
})
Upvotes: 3