objective c - Swift passing uninitialized object to block -
i have been trying figure out small thing quite easy objective c, not solve swift.
var loginviewcontroller: ssloginviewcontroller let completion = { loginviewcontroller.presentviewcontroller(ssfeedviewcontroller(), animated: true, completion: nil) } loginviewcontroller = ssloginviewcontroller(completion: completion)
the intention here pass ssloginviewcontroller completionblock present view controller. but, code above gives error.
variable 'loginviewcontroller' captured closure before being initialized.
delcaring uninitialized variable __block, objective c block take changed value within block.
it in objective c,
__block ssloginviewcontroller *loginviewcontroller; dispatch_block_t completion = ^ { [loginviewcontroller presentviewcontroller:[[ssfeedviewcontroller alloc] init] animated: yes completion:nil] }; loginviewcontroller = [[ssloginviewcontroller alloc] initwithcompletion:completion];
how can similar behavior achieved swift ?
it should initialized nil
(that's what's happening in objective-c code anyway; in objective-c arc, managed object pointers initialized nil
if not otherwise initialized). means need optional. can use implicitly-unwrapped optional not have deal optional syntax since know it's going nil
temporarily.
var loginviewcontroller: ssloginviewcontroller! let completion = { loginviewcontroller.presentviewcontroller(ssfeedviewcontroller(), animated: true, completion: nil) } loginviewcontroller = ssloginviewcontroller(completion: completion)
an additional problem, exists in objective-c code, there retain cycle. ssloginviewcontroller
object stores , has strong reference completion block, , block has strong reference ssloginviewcontroller
object. if know completion block exists while ssloginviewcontroller
object alive, can have capture weak reference loginviewcontroller
:
var loginviewcontroller: ssloginviewcontroller! let completion = { [weak loginviewcontroller] in loginviewcontroller.presentviewcontroller(ssfeedviewcontroller(), animated: true, completion: nil) } loginviewcontroller = ssloginviewcontroller(completion: completion)
Comments
Post a Comment