Monday 15 March 2010

swift closure stored and access as a variable -



swift closure stored and access as a variable -

i want implement callback in swift project used in objective-c need variable of type closure. closure should take parameter object , homecoming nothing.

var downloadcompleted: (mlbook) -> (void)!

when need trigger callback this:

if self.downloadcompleted { self.downloadcompleted(book) }

the compiler complains error message:

type '(mlbook) -> (void)!' not conform protocol 'booleantype'

if remove if statement compiler says:

property 'self.downloadcompleted' not initialized

even though it's implicitly unwrapped.

when seek callback:

bookstore.sharedinstance.downloadcompleted{(book: mlbook) -> () in println("print if got callback") }

i error message:

'(mlbook) -> ()' not convertible 'mlbook'

i'm more worried lastly error message i'm not quite sure trying tell me.

any help appreciated. thanks

here working example. have number of mistakes attached illustrates. note had download() method homecoming bool result can see in screen shot.

but, utilize of implicitly unwrapped optional (aka '!') incorrect. such optional used when value may nil assigned @ known time , not changed (see apple documentation description). downloadcompleted true optional (at to the lowest degree in illustration use). thus, improve code, turns out simpler is:

variables swift callback closures

No comments:

Post a Comment