In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:
// in .h
typedef void (^APLCalibrationProgressHandler)(float percentComplete);
typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error);
// in .m
#property (strong) APLCalibrationProgressHandler progressHandler;
#property (strong) APLCalibrationCompletionHandler completionHandler;
- (id)initWithRegion:(CLBeaconRegion *)region completionHandler:(APLCalibrationCompletionHandler)handler
{
self = [super init];
if(self)
{
...
_completionHandler = [handler copy];
..
}
return self;
}
- (void)performCalibrationWithProgressHandler:(APLCalibrationProgressHandler)handler
{
...
self.progressHandler = [handler copy];
...
dispatch_async(dispatch_get_main_queue(), ^{
_completionHandler(0, error);
});
...
}
So I'm trying to do the equivilant in Swift:
var completionHandler:(Float)->Void={}
init() {
locationManager = CLLocationManager()
region = CLBeaconRegion()
timer = NSTimer()
}
convenience init(region: CLBeaconRegion, handler:((Float)->Void)) {
self.init()
locationManager.delegate = self
self.region = region
completionHandler = handler
rangedBeacons = NSMutableArray()
}
The compiler doesn't like that declaration of completionHandler. Not that I blame it, but, how do I define a closure that can be set and used later in Swift?
The compiler complains on
var completionHandler: (Float)->Void = {}
because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking
a float argument. The following would assign a "do nothing" closure to the
completion handler:
var completionHandler: (Float)->Void = {
(arg: Float) -> Void in
}
and this can be shortened to
var completionHandler: (Float)->Void = { arg in }
due to the automatic type inference.
But what you probably want is that the completion handler is initialized to nil
in the same way that an Objective-C instance variable is inititialized to nil. In Swift
this can be realized with an optional:
var completionHandler: ((Float)->Void)?
Now the property is automatically initialized to nil ("no value").
In Swift you would use optional binding to check of a the
completion handler has a value
if let handler = completionHandler {
handler(result)
}
or optional chaining:
completionHandler?(result)
Objective-C
#interface PopupView : UIView
#property (nonatomic, copy) void (^onHideComplete)();
#end
#interface PopupView ()
...
- (IBAction)hideButtonDidTouch:(id sender) {
// Do something
...
// Callback
if (onHideComplete) onHideComplete ();
}
#end
PopupView * popupView = [[PopupView alloc] init]
popupView.onHideComplete = ^() {
...
}
Swift
class PopupView: UIView {
var onHideComplete: (() -> Void)?
#IBAction func hideButtonDidTouch(sender: AnyObject) {
// Do something
....
// Callback
if let callback = self.onHideComplete {
callback ()
}
}
}
var popupView = PopupView ()
popupView.onHideComplete = {
() -> Void in
...
}
I've provide an example not sure if this is what you're after.
var completionHandler: (_ value: Float) -> ()
func printFloat(value: Float) {
print(value)
}
completionHandler = printFloat
completionHandler(5)
It simply prints 5 using the completionHandler variable declared.
Closures can be declared as typealias as below
typealias Completion = (Bool, Any, Error) -> Void
If you want to use in your function anywhere in code; you can write like normal variable
func xyz(with param1: String, completion: Completion) {
}
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.
var completionHandler:([String:Any], Bool)->Void = { dict, success in
if success {
print(dict)
}
}
Calling the closure variable
self.completionHandler(["name":"Gurjinder singh"],true)
This works too:
var exeBlk = {
() -> Void in
}
exeBlk = {
//do something
}
//instead of nil:
exeBlk = {}
Depends on your needs there is an addition to accepted answer. You may also implement it like this:
var parseCompletion: (() ->Void)!
and later in some func assign to it
func someHavyFunc(completion: #escaping () -> Void){
self.parseCompletion = completion
}
and in some second function use it
func someSecondFunc(){
if let completion = self.parseCompletion {
completion()
}
}
note that #escaping parameter is a mandatory here
For me following was working:
var completionHandler:((Float)->Void)!
Related
Suppose we got a chain of closures, like so:
var myOtherVc: UIViewController! // get it somehow
self.dismiss(animated: true, completion: { [weak myOtherVc] in
myOtherVc?.present(sthElse, animated: true, completion: { [weak myOtherVc] in // <-- HERE
})
})
My question is if we captured variable myOtherVc in the topmost block as weak should we keep being explicit about weak in all the children blocks or is compiler smart enough to tell ARC to not retain?
Update
I guess I need to clarify, what if the block was escaping?
Also, i DO care about delayed deallocation. This is the whole point of using weak for me.
public func doWhatever(_ success: #escaping () -> Void) {
// do whatever
})
var myOtherVc: UIViewController! // get it somehow
self.dismiss(animated: true, completion: { [weak myOtherVc] in
SomeClass.doWhatever({ [weak myOtherVc] in // <-- HERE
myOtherVc?.present(sthElse, animated: true, completion: { [weak myOtherVc] in // <-- and HERE, too
})
})
})
We suppose all closures are escaping, so I made this playground and I conclude that you must capture your variable as weak in the latest closure that is using your variable and it won't infer its reference type from the parent or top closure:
typealias Closure = () -> Void
class A {
var closureA : Closure?
func runClosureA(closure: #escaping Closure) {
self.closureA = closure
closureA?()
}
func print() {
debugPrint("A is here!")
}
deinit {
debugPrint("A deinited")
}
}
another class which operates on chained closure:
class B {
func runClosureB(closure: #escaping Closure) {
closure()
}
func operate() {
let a : A = A()
runClosureB { [weak a] in
a?.runClosureA { [a] in
a?.print()
}
}
}
deinit {
debugPrint("B deinited")
}
}
The code is:
var b: B? = B()
b?.operate()
b = nil
It will prints:
// "A is here!"
// "B deinited"
But by changing the operate function to this:
func operate() {
let a : A = A()
runClosureB { [a] in
a.runClosureA { [weak a] in
a?.print()
}
}
}
The result will change to this:
"A is here!"
"A deinited"
"B deinited"
Update: In class A I made a strong reference to the closure as closureA, if you don't create the reference, there is no need to capture self as weak in closures.
In fact, it depends on which closure you are using and the relations between them and if there can be retained cycle so you should consider capturing the right closure as weak.
In your case, with present(_, animated:, completion:), the completion block is non-escaping so if you want to use weak reference you can use it but it is not necessary to use.
Non-escaping closures do not require [weak self] unless you care about delayed deallocation
Please check the article about weak, unowned references in nested closures.
I made a small test in the playground that shows me that the compiler is indeed quite smart and tells ARC not to retain.
class WeakThingy {
var variable: Int
init(variable: Int) {
self.variable = variable
}
deinit {
print("deinit WeakThingy")
}
}
class ClosureTest {
var maybeNil: WeakThingy
init(maybeNil: WeakThingy) {
self.maybeNil = maybeNil
}
deinit {
print("deinit ClosureTest")
}
func bien() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak maybeNil] in
print("first \(String(describing: maybeNil))")
maybeNil?.variable = 12
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
print("second \(String(describing: maybeNil))")
maybeNil?.variable = 12
}
}
}
}
var closureTest:ClosureTest? = ClosureTest(maybeNil: WeakThingy(variable: 12))
closureTest?.bien()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
closureTest = nil
}
What's printed is the following
first Optional(__lldb_expr_34.WeakThingy)
deinit ClosureTest
deinit WeakThingy
second nil
What happen here is that I pass maybeNil in the first closure as weak, but not in the second. Then I make it nil before the second closure gets executed. We can see in the output that it is well deallocated before entering the second closure.
Let's say I have a Swift class that stores a completion block, and does a few asynchronous tasks.
I want that block to be called by whichever of the tasks finishes first, but only that one - I don't want it to be called again when the second task finishes.
How can I implement this in a clean way?
As long as you don't need this to be thread safe, you can solve this problem with a fairly straightforward #propertyWrapper.
#propertyWrapper
struct ReadableOnce<T> {
var wrappedValue: T? {
mutating get {
defer { self._value = nil }
return self._value
}
set {
self._value = newValue
}
}
private var _value: T? = nil
}
Mark the completion block var with #ReadableOnce, and it will be destroyed after the first time it's value is read.
Something like this:
class MyClass {
#ReadableOnce private var completion: ((Error?) -> Void)?
init(completion: #escaping ((Error?) -> Void)) {
self.completion = completion
}
public func doSomething() {
// These could all be invoked from different places, like your separate tasks' asynchronous callbacks
self.completion?(error) // This triggers the callback, then the property wrapper sets it to nil.
self.completion?(error) // This does nothing
self.completion?(error) // This does nothing
}
}
I wrote up more of a detailed discussion of this here but the key thing to be aware of is that reading the value sets it to nil, even if you don't invoke the closure! This might be surprising to someone who isn't familiar with the clever property wrapper you've written.
There is already a standard expression of onceness. Unfortunately the standard Objective-C is unavailable in Swift (GCD dispatch_once), but the standard Swift technique works fine, namely a property with a lazy define-and-call initializer.
Exactly how you do this depends on the level at which you want onceness to be enforced. In this example it's at the level of the class instance:
class MyClass {
// private part
private let completion : (() -> ())
private lazy var once : Void = {
self.completion()
}()
private func doCompletionOnce() {
_ = self.once
}
// public-facing part
init(completion:#escaping () -> ()) {
self.completion = completion
}
func doCompletion() {
self.doCompletionOnce()
}
}
And here we'll test it:
let c = MyClass() {
print("howdy")
}
c.doCompletion() // howdy
c.doCompletion()
let cc = MyClass() {
print("howdy2")
}
cc.doCompletion() // howdy2
cc.doCompletion()
If you promote the private stuff to the level of the class (using a static once property), the completion can be performed only once in the lifetime of the entire program.
I'd like to use a method that return a result asynchronously using the delegate pattern within a closure.
Is it possible to reference the complete block within another function within the same class?
class A {
func performASyncTask(input:String, complete:(result:String) -> Void) {
let obj = Loader()
obj.delegate = self
obj.start()
// Loader() returns loaderCompleteWithResult(result:String) when completed
}
func loaderCompleteWithResult(result:String){
// Call complete function in performASyncTask .e.g
complete(result); // Calls the complete function in performASyncTask
}
}
I don't really understand what do you want to achieve. But you can declare function property and use it later:
class A {
var closureSaver: ((result:String) -> Void)?
func performASyncTask(input:String, complete:(result:String) -> Void) {
let obj = Loader()
obj.delegate = self
obj.start()
closureSaver = complete
complete(result: "a")
}
func loaderCompleteWithResult(result:String){
closureSaver?(result:result)
}
}
I made a mistake but I cannot see how to solve it. I would like to load all the assets from GameScene and send a Bool in a completion method. I use typealias : should it be renamed twice for the two files (gameScene and gameController)?
Then I have got an error on this line GameScene.loadSceneAssetsWithCompletionHandler{ :
((Bool) -> Void) is not convertible to 'GameScene'
Here is the code :
//gameController:
typealias OnComplete = (Bool) -> ()
override func viewDidLoad() {
super.viewDidLoad()
GameScene.loadSceneAssetsWithCompletionHandler{ (success:Bool)->Void in
println("2/ yes")
return
}
//gameScene : rewrite typealias?
typealias OnComplete = (Bool) -> ()
func loadSceneAssetsWithCompletionHandler( completion:OnComplete ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
self.loadSceneAssets()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println("1/ yes")
completion(true)
})//main
})//global
}
I read some threads that said to add a "return", but it does not solve the error here.
Thanks
It's almost working, but you've got a couple things going wrong here. First of all, you can't redeclare a typealias. Second of all you're calling loadSceneAssetsWithCompletionHandler as a class function when it's set up as an instance function. Note changes:
typealias OnComplete = (Bool) -> ()
class GameController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
GameScene.loadSceneAssetsWithCompletionHandler { success in
println("2/ yes")
return
}
}
}
class GameScene: UIViewController {
func loadSceneAssets() {
}
class func loadSceneAssetsWithCompletionHandler( completion:OnComplete ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let gameScene = GameScene()
gameScene.loadSceneAssets()
dispatch_async(dispatch_get_main_queue()) {
println("1/ yes")
completion(true)
}
}
}
}
I have the Test class with button_action optional closure:
class Test : CustomViewFromXib {
var button_action : (() -> ())?
#IBAction func button_pressed(sender: AnyObject) {
if let action = button_action {
action()
}
}
}
This is how I use this class:
let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = {
() -> () in
print("test")
}
I get EXC_BAD_ACCESS error at line:
test_view.button_action = {
() -> () in
print("test")
}
I don't know why, because I just want to set initial value. Is it possible to do it that way?
UPDATE:
I understood, that no one property or method can't be called from my object. Not only closures, but Strings (for example) too.
UPDATE 2:
This is my little example of code that reproduces the problem. I think I have a problem with initializers...
https://www.dropbox.com/s/1d8fvxm0es9b5n4/TestInit.zip
(XCode 6 Beta 5)
Write code
let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = {
() -> () in
print("test")
}
instead of
let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = { [unowned self]
() -> () in
print("test")
}
Here is exact detail theoretical answer
Shall we always use [unowned self] inside closure in Swift
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html