简体   繁体   English

如何快速将闭包用作函数的第二个参数?

[英]How to use a closure as second parameter of a function in swift?

I have a method that should do two things. 我有一种方法应该做两件事。 It should make a picture object, and return a closure thats called whenever a picture is finished downloaded locally. 它应该创建一个图片对象,并在图片下载完成后返回一个闭包(即闭合)。 This following code snippet tries to draw out what im trying. 下面的代码片段试图找出我正在尝试的内容。

typealias localURLForDownloadedImage = () -> (NSURL)

func pictureForDate(#date: NSDate) -> (picture: Picture?,downloadedImageURL: urlForDownloadedImage?) {
    // start downloading picture from a url
    let picture = Picture()

    // start downloading url
    let closure = urlForDownloadedImage(){
        // async method that returns when image is downloaded
        return NSURL(string: "downloadedimageurl://")
    }

    return (picture,closure)
}

The error i get for the closure to attribute is "urlForDownloadedImage is not compatible with () -> () -> $TO" 我为属性关闭给出的错误是“ urlForDownloadedImage与()->()-> $ TO不兼容”

As Xcode 6s autocomplete is broken still, how do you call this method? 由于Xcode 6s的自动完成功能仍然无效,您如何调用此方法? I am thinking somewhat like this: 我在想这样的事情:

pictureForDate(date: NSDate()) {
        // do stuff here after image was downloaded
    }

But this just gives a strange error. 但这只是一个奇怪的错误。

The closure should be 关闭应该是

let closure = { () -> NSURL in 
    // async method that returns when image is downloaded
    return NSURL(string: "downloadedimageurl://")
}

To call the method use: 要调用该方法,请使用:

let (pic, closure) = pictureForDate(date: NSDate())

now in pic and closure you have the 2 return values. 现在在picclosure您有2个返回值。 The closure must be unwrapped before using: 在使用之前,必须先解开闭包:

closure?()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM