我已经从plist中提取了项目并将其实现为字典,但是我不太确定如何从变量中解包并使这些项目可用。这是我的继承人:
import UIKit
class ViewController: UIViewController,
UITableViewDataSource {
// Loading in the PLIST file
override func viewDidLoad() {
super.viewDidLoad()
}
var courses = loadCSCourses()
//variables
var courseData = courses["CS 1400"]
var shortDescription = courseData["ShortDescription"]
var courseKeys = Array(courses.keys)
@IBOutlet weak var mySwitch: UISwitch!
@IBOutlet weak var tableView: UITableView!
@IBAction func whenSwitchOn (sender:AnyObject) {
if (mySwitch.isOn){
self.tableView.reloadData()
}
}
func sortingCourseKeys() {
courseKeys.sort()
}
// The number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses!.count
}
// The number of cells in each row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//Naming the Title and Subtitle line
cell.textLabel?.text = "course name"
cell.detailTextLabel?.text = "course description"
cell.accessoryType = .checkmark
return cell
}
// Selecting and deslecting rows
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = courseKeys[indexPath.row]
if cell.contains(courseKeys[indexPath.row]) {
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
return
}
}
func loadCSCourses() -> [String : [String : String]]? {
let pListFileURL = Bundle.main.url(forResource: "CSCourses", withExtension: "plist", subdirectory: "")
if let pListPath = pListFileURL?.path,
let pListData = FileManager.default.contents(atPath: pListPath) {
do {
let pListObject = try PropertyListSerialization.propertyList(from: pListData, options:PropertyListSerialization.ReadOptions(), format:nil)
guard let maybeCourses = pListObject as? [String : [String : String]] else {
return nil
}
return maybeCourses
} catch {
print("Error reading CSCourses plist file: \(error)")
return nil
}
}
return nil
}
我收到错误:无法在属性初始化程序中使用实例成员“课程”;属性初始化程序在“自我”可用之前运行和可选类型'[String:[String:String]]的值?”必须解包以引用基本类型为'[String:[String:String]]'
的成员'subscript'任何提示,链接或帮助,将不胜感激。谢谢大家。
您面临的问题是,在初始化self之前,您正在使用类方法。您有几种选择:
覆盖init函数并在此处设置变量
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
courses = loadCSCourses()
}
将变量设为惰性变量
lazy var courses = loadCSCourses()
将函数loadCSCourses()设为静态,尽管我不建议这样做。
请记住您的定义方式:
var courseData = courses["CS 1400"]
var shortDescription = courseData["ShortDescription"]
var courseKeys = Array(courses.keys)
还为时尚早,在定义self之后(或遵循2.选项)将其移至init)>