我不理解闭包捕获数据的这个概念。有人可以使用闭包来编写示例代码,这些闭包显示数据永远不会被破坏。我已经阅读了Apple文档,但我仍然感到困惑。并且还怎么“无主”和“弱”使封闭任何区别...闭包如何捕获数据?
class TableViewController: UITableViewController {
var allWords = [String]()
var usedWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
if let allWordsPath = Bundle.main.path(forResource: "start", ofType: "txt"){
if let startWords = try? String(contentsOfFile: allWordsPath){
allWords = startWords.components(separatedBy: "\n")
}else{
allWords = ["Cake"]
}
startGame()
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Make Word", style: .plain, target: self, action: #selector (makeWord))
}
func startGame(){
allWords = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allWords) as! [String]
title = allWords[0]
usedWords.removeAll(keepingCapacity: true)
}
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
}
func makeWord() {
let ac = UIAlertController(title: "Add Word", message: nil, preferredStyle: .alert)
ac.addTextField(configurationHandler: nil)
let submit = UIAlertAction(title: "Submit", style: .default){ [unowned self,ac]
(action: UIAlertAction!) in
let answer = ac.textFields?[0]
self.submit(answer: (answer?.text)!)
}
ac.addAction(submit)
present(ac,animated: true)
}
var number = 10
func submit(answer: String){
usedWords.append(answer)
tableView.reloadData()
}
这里怎么做无主的工作,如果我们没有明确重新分配的东西..
http://alisoftware.github.io/swift/closures/2016/07/25/closure-capture-1/ – Pochi
我不明白他的榜样。 –
检查我的答案。 Btw关闭不保证你的数据不会被破坏。它们只是允许您指定应该如何处理数据,以及在被销毁的情况下如何处理。它完全有效的将变量设置为“弱”,然后在封闭内部简单地检查它。 – Pochi