[iOS] Pass optional block or closure to a function in Swift

Posted in :

古時候objective-c 寫法:

- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;

[object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){
	NSLog(result);
}];

swift 寫法:

func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
	...
	completion("we finished!")
}

加入紅色框框處就做完了,結束,在爸爸的主程式準備一個

    func imageUploadComplete(ret: String) {

        print("Hello:" + ret)

    }

在副程式存取 completion:

completion(dataString!)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *