我不理解閉包捕獲數據的這個概念。有人可以使用閉包來編寫示例代碼,這些閉包顯示數據永遠不會被破壞。我已經閱讀了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