我正在编写一个基本的iOS应用来测试我的Swift知识并继续练习。在我的应用程序中,用户键入婴儿的名称,然后打开或关闭开关以设置性别/性别,并更改系统颜色。 之后,该名称用于在以下代码块中填写名为" firstWords"的UITextView:
// Save name entered into text field
@IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
if boyGirlSwitch.isOn {
let sex = ("boy", "his", "he", "Boy", "His", "He")
} else {
let sex = ("girl", "her", "she", "Girl", "Her", "She")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
我在(sex.5)
内的元组firstWords
上一直收到错误消息:" Use of unresolved identifier 'sex'
"
据我了解,常量sex
是在if
语句中声明的,编译器确实以任何方式通过它,因此它确实被识别并声明。
问题:为什么我收到错误?
提前致谢!这是我的代码的屏幕截图: Screenshot of block of code as described above, including the compiler/build-error
答案 0 :(得分:2)
这是一个范围问题。 sex
仅在else
子句中可用。
您可以像这样修复
// Save name entered into text field
@IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
var sex : (String, String, String, String, String, String)
if boyGirlSwitch.isOn {
sex = ("boy", "his", "he", "Boy", "His", "He")
} else {
sex = ("girl", "her", "she", "Girl", "Her", "She")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
这种方式sex
在整个IBAction
的范围内定义,最终可用。
如果您使用默认值预先声明它,也可以跳过一个条件:
// Save name entered into text field
@IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
var sex = ("girl", "her", "she", "Girl", "Her", "She")
if boyGirlSwitch.isOn {
sex = ("boy", "his", "he", "Boy", "His", "He")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
维基百科上有一篇关于变量范围的文章:https://en.wikipedia.org/wiki/Scope_(computer_science)