Search code examples
iosobjective-cswiftblock

Block conversion in swift from Objective-c


How to convert following block from Objective-C to Swift. Am using Objective-C files in Swift using bridge header. But small confusion in block conversion

Objective-C Block:

+ (void) while:(id)obj name:(void(^)(type*))callback;

Sample output:

[Sub while:keeper viewControllerChanged:^(NSString* newNickname) {
        NSLog(@"\nVC2- Now screen is in: %@", newNickname);
    }];

How to convert this in swift ?

EDIT: Swift block error is

Sub.while(obj: AnyObject!, viewControllerChanged: ((String!) -> Void)!)

Solution

  • When you define :

    class func while1(obj:AnyObject, callback name:((newNickname:NSString?) -> Void)) {
    
    
    }
    

    And when call function :

    self.while1(self) { (newNickname) -> Void in
    
            print("\nVC2- Now screen is in:" + "\(newNickname)")
        }
    

    EDIT :

    Okay, Then you just want to call it from swift..right..? Then use this statement :

    ClassName.while1(obj as AnyObject) { (nickName:String!) -> Void in
    
            print(nickName)
        }
    

    But first make sure that in your definition statement "type" indicates for what DataType, so please define there actual DataType

    + (void)while:(id)obj name:(void(^)(type*))callback;
    

    to --> For example :

    + (void)while1:(id)obj name:(void(^)(NSString *))callback;
    

    And one more thing to note that while in built in keyword, please do not use it if possible.