在 Swift 中从闭包内调用异步共享实例方法的语法
Syntax to Call Asynchronous Shared Instance Method from Within Closure in Swift
我在使用闭包中调用共享实例方法的语法时遇到问题:
这是我的代码:
func getContactImage (contact:Contacts, completion:@escaping (_ myimage: UIImage)->()){//open 1 method
var animg = UIImage(named:"default.png")!
let surl = "https://~/contactimage.png"
Utilities.shared.downloadImage(surl: surl as NSString, completion: image as UIImage ->Void in animg = img)
completion(animg)
}
行 Utilities.shared.downloadImage 给出了几个错误,包括:
Cannot convert value of type 'UIAccessibilityTraits' (aka 'UInt64') to type 'UIImage' in coercion
共享实例方法如下所示:
@objc func downloadImage(surl: NSString, completion : @escaping (UIImage) -> Void ) {
//download image
}
从闭包中调用共享实例方法的正确语法是什么?
使用
Utilities.shared.downloadImage(surl) { (img) in
// use img here
}
也改函数
@objc func downloadImage(_ surl: String, completion : @escaping (UIImage) -> Void ) { }
func getContactImage (contact:Contacts, completion:@escaping (_ myimage: UIImage)->()){//open 1 method
var animg = UIImage(named:"default.png")!
let surl = "https://~/contactimage.png"
Utilities.shared.downloadImage(surl) { (img) in
completion(img)
}
}
顺便说一句,鼓励使用 SDWebImage
我在使用闭包中调用共享实例方法的语法时遇到问题:
这是我的代码:
func getContactImage (contact:Contacts, completion:@escaping (_ myimage: UIImage)->()){//open 1 method
var animg = UIImage(named:"default.png")!
let surl = "https://~/contactimage.png"
Utilities.shared.downloadImage(surl: surl as NSString, completion: image as UIImage ->Void in animg = img)
completion(animg)
}
行 Utilities.shared.downloadImage 给出了几个错误,包括:
Cannot convert value of type 'UIAccessibilityTraits' (aka 'UInt64') to type 'UIImage' in coercion
共享实例方法如下所示:
@objc func downloadImage(surl: NSString, completion : @escaping (UIImage) -> Void ) {
//download image
}
从闭包中调用共享实例方法的正确语法是什么?
使用
Utilities.shared.downloadImage(surl) { (img) in
// use img here
}
也改函数
@objc func downloadImage(_ surl: String, completion : @escaping (UIImage) -> Void ) { }
func getContactImage (contact:Contacts, completion:@escaping (_ myimage: UIImage)->()){//open 1 method
var animg = UIImage(named:"default.png")!
let surl = "https://~/contactimage.png"
Utilities.shared.downloadImage(surl) { (img) in
completion(img)
}
}
顺便说一句,鼓励使用 SDWebImage