Nicholas  Bear
Nicholas Bear

Reputation: 71

How to Access a variable inside the function and then use it?

I am trying to access a variable i that is inside the function checkUser(). The next thing is the if statement, if i == 0 that should println("Displaying Picture of Someone else")

The code at the bottom does not work, because the function checkUser does not return i value and I get an error:use of unresolved identifier 'i', however after poking around and adjusting the code to:

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

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

and implementing it, I get an error int is not convertible to void. What are my options to make it work?


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

Upvotes: 0

Views: 135

Answers (5)

Nicholas  Bear
Nicholas Bear

Reputation: 71

Thanks you guys for all the replies. Does indeed make sense; I created a function and moved it inside the completion block and It worked.

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!)")}

}
}

Upvotes: 0

saurabh
saurabh

Reputation: 6775

If u want to display someone else's picture based on the result count of request, you can call a function instead of creating and checking for condition:

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

Upvotes: 1

Rog
Rog

Reputation: 17170

The definition of the variable i (var i = objects.count) is defined in a different scope from the place where you check its value. Specifically it is defined in the anonymous closure you pass to reqest.findObjectsInBackgroundWithBlock

You could fix the compile time error by defining i above the call to reqest.findObjectsInBackgroundWithBlock. However that would just give you a runtime error.

What's happening here is that the code inside {} directly after reqest.findObjectsInBackgroundWithBlock is run after the call completes which means that it'll be run after your test if i == 0{...

More that code up inside the previous block.

Upvotes: 0

Timothy Walters
Timothy Walters

Reputation: 16874

In the second bit of code you simply need to move that code inside the completion block where i is defined.

It is a matter of understanding the nature async code execution.

Inside your completion block you can call methods to let the UI or other parts of the code know that you're done. You are correct that you cannot return values like you would normally for in-line code.

It helps to think of async code as you asking for something to be done "when you get around to it". You need to decide how that code should let you know that it got around to it.

Upvotes: 0

Miknash
Miknash

Reputation: 7948

From your code :

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

I would say that you defined variable inside the block but tried to use it outside. That won't work.

Try to set var i : Int = 0 below var request = PFUser.query()

Also, @Frank Schmitt has the point. remove the bracelets.

Upvotes: 0

Related Questions