0

我正在编写一个基本的 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语句中声明的,编译器确实会通过它,所以它确实被识别和声明。 问题:为什么我会收到错误消息?

提前致谢!这也是我的代码的屏幕截图: 如上所述的代码块屏幕截图,包括编译器/构建错误

4

1 回答 1

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)

于 2017-06-13T07:16:16.600 回答