App Team
App Team

Reputation: 69

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)!)

Upvotes: 2

Views: 372

Answers (3)

vien vu
vien vu

Reputation: 4337

You can call like this:

YourClassName.while2(Yourparameter , name: {(nickName : String) -> Void in

    })

I hope this help.

Upvotes: 1

VRAwesome
VRAwesome

Reputation: 4803

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.

Upvotes: 1

Moriya
Moriya

Reputation: 7906

I'm not sure if you are asking how to write blocks in swift or if I'm not completely getting your question. But if it's the first then...

(void(^)(type*))callback

becomes

callback: (param:type*)->(returnType*)

i.e.

func doSomething(callback:((number:Int)->()))

is called like

doSomething(callback:{number in 
    print("\(number)")
})

Upvotes: 0

Related Questions