“ViewController”类型的Swift值没有名为“Self”的成员错误

时间:2017-12-08 19:13:43

标签: ios swift xcode

我试图了解Swift中的后端闭包,这段代码在promptForAnswer()中给出了一个错误。具体来说,我收到一个Xcode错误,上面写着:

  

“ViewController”类型的值没有名为“Self”的成员

...即使我已经在代码中声明了它。

有人可以解释什么是错的吗?

import UIKit
import GameplayKit

var allWords = [String]()
var usedWords = [String]()

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer))

        if let startWordsPath = Bundle.main.path(forResource: "start", ofType: "txt") {
            if let startWords = try? String(contentsOfFile: startWordsPath) {
                allWords = startWords.components(separatedBy: "\n")
            }
        } else {
            allWords = ["silkworm"]
        }
        startGame()
    }

    @objc func promptForAnswer() {
        let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
        ac.addTextField()

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
            [unowned self, ac] (action: UIAlertAction) in
            let answer = ac.textFields![0]
            self.submit(answer: answer.text!) // Value of type "ViewController" has no member type "self"
        }

        ac.addAction(submitAction)
        present(ac, animated: true)
    }

    func startGame() {
        allWords = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allWords) as! [String]
        title = allWords[0]
        usedWords.removeAll(keepingCapacity: true)
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usedWords.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath)
        cell.textLabel?.text = usedWords[indexPath.row]
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:0)

当我使用默认工具链(Swift 4.0)将代码粘贴到Xcode 9.2中的游乐场时,我在您指定的行上显示此错误:

  

'ViewController'类型的值没有成员'submit'

您可以通过向控制器添加如下所示的方法来解决此错误:

func submit(answer: String) {
  // ...
}

在您使用的任何编译器版本中都可能存在错误。或许这只是一个糟糕的一天。有时会发生奇怪的事情。 ¯\ _(ツ)_ /¯

即使是次要版本的Swift,事情也会发生很大变化,因此请确保包含Xcode版本和您正在使用的工具链。它使重现您的体验变得更加容易。