[英]How can I initialise a global variable in a function for further use in Swift?
Thanks in advance for the help. 先谢谢您的帮助。 I'm just starting out on swift and I'm using Xcode to to attempt at building a fairly simple app.
我只是快速入门,我正在使用Xcode尝试构建一个相当简单的应用程序。
class ViewController: UIViewController {
@IBOutlet var text: UITextField!
@IBOutlet var Lable: UILabel!
@IBOutlet var Button: UIButton!
@IBOutlet var message1: UITextField!
@IBOutlet var Button2: UIButton!
var name = 0
@IBAction func Button(sender: UIButton) {
var name = text.text.toInt()
}
@IBAction func Button2(sender: UIButton) {
var code = Array (message1.text).map{String($0).toInt()! }
for var n = 0 ; n < code.count; n++
{
code[n] = code[n] + name
}
var StringArray = (code : String())
if name != 0
{
message1.text = "name variable is inisialised"
}
else
{
message1.text = "Error name is not initialised"
}
}
When I try this out I always get the same answer that Name is not initialised as it still has the global inisialisation Name = 0 at the end but further down I initialise it to the int value whithin the text field yet it doesn't update the global variable. 当我尝试此方法时,我总是会得到一个相同的答案,即名称未初始化,因为它的末尾仍然具有全局inisialization名称= 0,但进一步向下,我将其初始化为文本字段中的int值,但它不会更新全局变量。 If You could give me some code to use to initialise name as a global variable and use it in the other functions That would be great.
如果您可以给我一些代码来将名称初始化为全局变量,然后在其他函数中使用它,那就太好了。 Thank you for your time!
感谢您的时间!
One problem (not the only problem, as you'll later discover) is this: 一个问题(不是唯一的问题,您稍后会发现)是:
var name = 0
@IBAction func Button(sender: UIButton) {
var name = text.text.toInt() // this is a DIFFERENT "name"
}
You said var
in the second one, which makes that name
a different name
- a local variable inside the function. 您在第二个变量中说了
var
,这使该name
成为另一个 name
-函数内部的局部变量。 Instead of using the global, you declared a different variable. 您声明了一个不同的变量,而不是使用全局变量。 In slightly more technical terms, you have redeclared this variable, overshadowing the global.
用稍微更专业的术语来说,您已经重新声明了此变量,从而使全局变量黯然失色。
Change your Button()
function to: 将您的
Button()
函数更改为:
@IBAction func Button(sender: UIButton) {
// Handle the case where toInt() fails, by returning nil/.None
// For example, shown below, set name to `0`
name = text.text.toInt() ?? 0
}
Also name
is a particularly bad name to use when assigning it a number. 同样,
name
是在分配编号时使用的特别糟糕的名称。 Maybe name_index
is better? 也许
name_index
更好?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.