gpt4 book ai didi

ios - 类没有初始化器 : Swift Error

转载 作者:IT王子 更新时间:2023-10-29 05:16:47 25 4
gpt4 key购买 nike

我的 ViewController 有问题。

我的代码有一个关于初始化程序的错误,我不明白为什么。

请花点时间看看我的代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

let sectionsTableIdentifier = "SectionsTableIdentifier"

var names: [String: [String]]!
var keys: [String]!

@IBOutlet weak var tableView: UITableView!

var searchController: UISearchController

//methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: sectionsTableIdentifier)

let path = NSBundle.mainBundle().pathForResource("sortednames", ofType: "plist")

let namesDict = NSDictionary(contentsOfFile: path!)
names = namesDict as! [String: [String]]
keys = namesDict!.allKeys as! [String]
keys = keys.sort()

let resultsController = SearchResultsController()

resultsController.names = names
resultsController.keys = keys
searchController = UISearchController(searchResultsController: resultsController)

let searchBar = searchController.searchBar
searchBar.scopeButtonTitles = ["All", "Short", "Long"]
searchBar.placeholder = "Enter a search term"

searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
searchController.searchResultsUpdater = resultsController

}

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


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return keys.count
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let key = keys[section]
let nameSection = names[key]!
return nameSection.count
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return keys[section]
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(sectionsTableIdentifier, forIndexPath: indexPath) as UITableViewCell

let key = keys[indexPath.section]
let nameSection = names[key]!
cell.textLabel!.text = nameSection[indexPath.row]

return cell
}

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {


return keys
}

}

问题是什么?错误是该类没有初始化程序。我没有没有值(value)的变量。

最佳答案

有问题的线路是

var searchController: UISearchController

改成

var searchController: UISearchController!

或者如果您没有在 View 生命周期中初始化它,请使用 optional 来避免崩溃:

var searchController: UISearchController?

关于ios - 类没有初始化器 : Swift Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32718428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com