Search code examples
iosswiftfunctionvar

access var in another function


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.


Solution

  • 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