Reputation: 3
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?
Upvotes: 0
Views: 90
Reputation: 285270
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.
Upvotes: 2
Reputation: 854
You are declaring a new Finalvar
again 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
Upvotes: 2