0

I am trying to figure out how I can use a variable outside of the function it was created in without using return. Example:

import UIKit var Finalvar = "test" func test(var1: String) { var Finalvar = var1 } test(var1: "Done") print(Finalvar) 

as output I get "test" instead of "done", how can I change that?

2
  • 1
    remove the var inside function. You are redeclaring the variable Commented Nov 2, 2017 at 12:18
  • 1
    Don't create a new variable inside the function, just do Finalvar = var1. However, most importantly, read the Swift book as a start, you seem to lack key concepts such as scopes of variables. Also variable and function names should be lower-camelCase (finalvar). Commented Nov 2, 2017 at 12:19

2 Answers 2

2

Finalvar is not Finalvar

The global variable Finalvar and the local variable Finalvar are two different objects.

If you declare a local variable with the same name as a global variable the global variable is hidden.

Remove the var keyword in the function

var finalVar = "test" func test(var1: String) { finalVar = var1 } test(var1: "Done") print(finalVar) 

In a class or struct you can use self to indicate to access the property.

self.finalVar = var1 

Note : Variable (and function) names are supposed to start with a lowercase letter.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems to be global function so self will not work
Probably better to use a inout keyword
2

You are declaring a new Finalvaragain in your func test(), just leave out the declaration out in your function. The code below should work:

import UIKit var finalVar = "test" func test(var1: String) { finalVar = var1 } test(var1: "Done") print(finalVar) 

One additional important thing -> please begin your variables with lowercase instead of a capital letter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.