简体   繁体   English

如何在其创建的函数之外使用变量

[英]How do I use a variable outside of the function it was created in

I am trying to figure out how I can use a variable outside of the function it was created in without using return. 我试图弄清楚如何在不使用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? 作为输出,我得到“测试”而不是“完成”,我该如何改变呢?

Finalvar is not Finalvar Finalvar不是Finalvar

The global variable Finalvar and the local variable Finalvar are two different objects. 全局变量 Finalvar局部变量 Finalvar是两个不同的对象。

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关键字

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来指示访问属性。

self.finalVar = var1

Note : Variable (and function) names are supposed to start with a lowercase letter. 注意:变量(和函数)名称应以小写字母开头。

You are declaring a new Finalvar again in your func test() , just leave out the declaration out in your function. 您将在func test()再次声明一个新的Finalvarfunc test()声明。 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 还有一件重要的事情->请以小写字母而不是大写字母开头的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM