-1

i'm facing a problem while trying to access to a variable which is declared in an other function.

this is my code :

@IBAction func Addbutton(sender: UIButton) {

        myImageUploadRequest()

    var titlestring: NSString = titre.text as NSString //Var i want to access
    var description:NSString = desc.text as NSString
    var price : NSString = prix.text as NSString

}

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
    var body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    //here i want to access to the titlestring var declared in my addButton func
    println(titlestring)

    let filename = titlestring
}

I tried to return the var but i do not success.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
f1rstsurf
  • 637
  • 1
  • 6
  • 22
  • All variables declared in a function are 'destroyed' when you exit the function. So titlestring does not exist outside of Addbutton(). You need to declare titlestring outside of the functions, or return it from Addbutton – Arno van Lieshout Sep 06 '15 at 12:57
  • You cannot access local variables declared in other methods. It is simply not possible. Perhaps if you describe the actual problem you are solving on the high level (i.e. creating a button to do XYZ and producing a description of PQR that must include some data from the button) someone could suggest a better approach. – Sergey Kalinichenko Sep 06 '15 at 12:58

2 Answers2

1

Start by creating a variable outside the functions but inside your class. (a global variable)

var titleString:NSString?

We will make this an optional string since it doesn't have any initial values.

inside your function you can write to this string.

titleString = title.text as NSString //Var i want to access

you can then check to see if your string has a value (since it is an optional string)

if let title = titleString{
    println(title)
}

extra information. Why are you using NSString as supposed to the swift native String?
Read this answer to see why native types are better.

It is common practice to use camelcasing for your variables.
titleString as opposed to titlestring this'll make it much easier to read

Community
  • 1
  • 1
milo526
  • 5,012
  • 5
  • 41
  • 60
  • I already tried this way , but it return "nil", however if i put a control at the end of "AddButton" i get the value. – f1rstsurf Sep 06 '15 at 13:20
0

declare this outside the IBAction at the top of your class

var titlestring : NSString = ""

// then the rest of your code now you can access the string variable

Ahmed Samir
  • 291
  • 3
  • 6