1. 程式人生 > >[iOS] Pass optional block or closure to a function in Swift

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

古時候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!)