如何访问函数内部的变量然后使用它?

时间:2015-03-23 06:04:19

标签: swift parse-platform

我正在尝试访问函数i中的变量checkUser()。接下来是if语句,if i == 0println("Displaying Picture of Someone else")

底部的代码不起作用,因为函数checkUser没有返回i值而我得到一个错误:use of unresolved identifier 'i',但是在调整并调整代码之后:

func checkUser() -> (Int?) {
    var i = 0
    return (i)
}

var (i) = checkUser()
if i == 0{
    println("Value is set")
}

并实施它,我收到错误int is not convertible to void。我有什么选择让它发挥作用?


func checkUser(){
    var reqest = PFUser.query()

    reqest.whereKey("username", equalTo: self.user.username)
    reqest.whereKey("check", equalTo: true)
    reqest.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!)-> Void in
        if error == nil {
            println("Successfully retrieved \(objects.count) item.")

            var i = objects.count // variable that holds objects.count

            if let objects = objects as? [PFObject] {
                for object in objects {
                    println(object.objectId)
                    if object["check"] as Bool == true{
                        println("Displaying Picture of You")
                    }
                }
            }
        } else {
            // Log details of the failure
            println("Error: \(error) \(error.userInfo!)")
        }
    }

    if i == 0{
        println("Displaying Picture of Someone else")
    }
}

5 个答案:

答案 0 :(得分:1)

如果您想根据请求的结果计数显示其他人的图片,您可以调用函数而不是创建和检查条件:

func checkUser(){
var reqest = PFUser.query()

reqest.whereKey("username", equalTo: self.user.username)
reqest.whereKey("check", equalTo: true)
reqest.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!)-> Void in
if error == nil {
  println("Successfully retrieved \(objects.count) item.")

  if (objects.count == 0) {
    displayPicture()
  }

  if let objects = objects as? [PFObject] {
    for object in objects {
      println(object.objectId)
      if object["check"] as Bool == true{
        println("Displaying Picture of You")
      }
    }
  }
} else {
  // Log details of the failure
  println("Error: \(error) \(error.userInfo!)")
}
}

displayPicture() {
   println("Displaying Picture of someone else")
  }
}

答案 1 :(得分:0)

从你的代码:

func checkUser(){
var reqest = PFUser.query()

reqest.whereKey("username", equalTo: self.user.username)
reqest.whereKey("check", equalTo: true)
reqest.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]!, error: NSError!)-> Void in
    if error == nil {
        println("Successfully retrieved \(objects.count) item.")

        var i = objects.count // variable that holds objects.count

        if let objects = objects as? [PFObject] {
            for object in objects {
                println(object.objectId)
                if object["check"] as Bool == true{
                    println("Displaying Picture of You")
                }
            }
        }
    } else {
        // Log details of the failure
        println("Error: \(error) \(error.userInfo!)")
    }
}

if i == 0{
    println("Displaying Picture of Someone else")
}
}

我会说你在块中定义了变量但是试图在外面使用它。那不会起作用。

尝试将var i : Int = 0设置为var request = PFUser.query()

以下

另外,@弗兰克施密特有重点。取下手镯。

答案 2 :(得分:0)

在第二位代码中,您只需将代码移动到定义i的完成块内。

这是理解自然异步代码执行的问题。

在完成块中,您可以调用方法让UI或代码的其他部分知道您已完成。你是正确的,你不能像通常的内联代码那样返回值。

当您要求“完成任务”时,有必要考虑异步代码。你需要决定那段代码应该让你知道它是如何解决它的。

答案 3 :(得分:0)

变量i(var i = objects.count)的定义在与检查其值的位置不同的范围内定义。具体来说,它是在您传递给reqest.findObjectsInBackgroundWithBlock

anonymous closure中定义的

您可以通过在调用reqest.findObjectsInBackgroundWithBlock之上定义i来修复编译时错误。但是,这只会给你一个运行时错误。

这里发生的事情是{}之后reqest.findObjectsInBackgroundWithBlock内的代码在调用完成后运行,这意味着它将被运行在你的考试if i == 0{...

之后

在上一个区块内添加更多代码。

答案 4 :(得分:0)

谢谢各位回复。确实有意义;我创建了一个函数并将其移动到完成块中并且它工作正常。

func checkUser(){

func displayPicture() {
    println("Displaying Picture of someone else")
}

var reqest = PFUser.query()
//reqest.whereKey("college", equalTo: self.user.valueForKey("college"))
reqest.whereKey("username", equalTo: self.user.username)
reqest.whereKey("check", equalTo: true)
reqest.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]!, error: NSError!)-> Void in
    if error == nil {

println("Successfully retrieved \(objects.count) item.")

        if(objects.count == 0){
            displayPicture()
        }



if let objects = objects as? [PFObject] {
            for object in objects {
                println(object.objectId)
                if object["check"] as Bool == true{
                    println("Displaying Picture of You")


                    self.textFieldName.hidden = true
                    self.checkCommand.hidden = true

                    let userName = PFUser.currentUser().valueForKey("name")as String
                    //self.firstName.text = userName // Displays current username
                    self.personName = userName


                    let userPicture = PFUser.currentUser().valueForKey("profilePic") as PFFile
                    userPicture.getDataInBackgroundWithBlock{
                        (imageData:NSData!,error:NSError!) -> Void in
                        if error == nil{
                            let image:UIImage! = UIImage(data: imageData)
                            self.profilePic.image = image //displays current user picture
                        }
                        else {
                            // Log details of the failure
                            println("Picture not downloaded: \(error) \(error.userInfo!)")
                        }
                    }


                }
                }}} else {
        // Log details of the failure
        println("Error: \(error) \(error.userInfo!)")}

}
}