我在从外部函数调用类中的变量时遇到问题。
Swift 给出以下错误:使用未解析的标识符“imageFilename”
我怎样才能解决它?我应该如何获取Filename
变量的值?
我的代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if (collectionView == self.collectionView1)
{
let cell : FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! FeaturedCollectionViewCell
let imgURL: NSURL = NSURL(string: "http://localhost:9001/feature-0.jpg")!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func display_image()
{
let imageFilename = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
task.resume()
cell.featuredImage.image = UIImage(named: imageFilename)
return cell
}
}
最佳答案
如果您在函数外部声明变量并在函数内部设置值,怎么样?然后您就可以访问该变量及其值。
您的问题肯定是您无法访问该变量,因为它只是在函数内部知道。
代码:
像这样尝试一下...
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if (collectionView == self.collectionView1)
{
let cell : FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! FeaturedCollectionViewCell
var imageFilename: UIImage
let imgURL: NSURL = NSURL(string: "http://localhost:9001/feature-0.jpg")!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func display_image()
{
imageFilename = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
task.resume()
cell.featuredImage.image = UIImage(named: imageFilename)
return cell
}
}
如果这对您有用,请给我写信。
关于swift - swift中从外部函数调用值变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093850/