programing tip

Swift에서 클로저를 변수로 저장

itbloger 2020. 6. 29. 08:11
반응형

Swift에서 클로저를 변수로 저장


Objective-C에서 블록의 입력 및 출력을 정의하고 메소드에 전달 된 블록 중 하나를 저장 한 다음 나중에 해당 블록을 사용할 수 있습니다.

// 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);
            });
     ...
}

그래서 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()
}

컴파일러는 completionHandler 선언을 좋아하지 않습니다. 내가 그것을 비난하지는 않지만 나중에 Swift에서 설정하고 사용할 수있는 클로저를 어떻게 정의합니까?


컴파일러는

var completionHandler: (Float)->Void = {}

오른쪽은 적절한 서명의 종결, 즉 부동 인수를 취하는 종결이 아니기 때문입니다. 다음은 완료 처리기에 "아무것도하지 않음"폐쇄를 지정합니다.

var completionHandler: (Float)->Void = {
    (arg: Float) -> Void in
}

이 단축 될 수 있습니다

var completionHandler: (Float)->Void = { arg in }

자동 유형 유추로 인해.

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) {
    println(value)
}

completionHandler = printFloat

completionHandler(value: 5)

It simply prints 5 using the completionHandler variable declared.


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)

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) {
}

This works too:

var exeBlk = {
    () -> Void in
}
exeBlk = {
    //do something
}
//instead of nil:
exeBlk = {}

For me following was working:

var completionHandler:((Float)->Void)!

참고URL : https://stackoverflow.com/questions/24603559/store-a-closure-as-a-variable-in-swift

반응형