swift - swift中从外部函数调用值变量

标签 swift variables global-variables call xcode7

我在从外部函数调用类中的变量时遇到问题。

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
    }
}

Image capture link

最佳答案

如果您在函数外部声明变量并在函数内部设置值,怎么样?然后您就可以访问该变量及其值。

您的问题肯定是您无法访问该变量,因为它只是在函数内部知道。

代码:

像这样尝试一下...

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/

相关文章:

swift - Xcode 6.3 代码完成太慢

没有变量扩展的 bash 选项卡完成?

javascript - 访问名称中具有特定值的特定数组

c++ - 如何在宿主程序调用 main() 函数之前构造 DLL 模块中的全局对象?

c++ - C++ 中的全局变量

C:如何舍入一个全局变量?

ios - PushViewController 没有工作

ios - @IBInspectable 何时设置?

ios - 如何根据swift中的内容增加TableViewCell的高度

javascript - 将变量与 xmlDoc.getElementsByTagName 一起使用