我有两个班级成绩和老师。
class Grade: NSObject {
var grade:String = ""
var id:String = ""
init(from dictionary:Parameters) {
self.grade = dictionary["grade"] as? String ?? ""
self.id = dictionary["grade_id"] as? String ?? ""
}
}
class Teacher: NSObject {
var teacher:String = ""
var id:String = ""
init(from dictionary:Parameters) {
self.teacher = dictionary["teacher"] as? String ?? ""
self.id = dictionary["teacher_id"] as? String ?? ""
}
}
因此,我想创建一个将包含id和title的通用类。它可以从两个类中获取数据。
我正在使用以下方法,但我认为这不是实现的最佳方法。让我知道什么是最好的方法。
func prepareDataSourceForPicker(pickerType:PickerType) {
var pickerArr = [PickerItem]()
if pickerType == .grade {
for value in self.arrGrades {
let pickerItem:PickerItem = PickerItem()
pickerItem.title = value.grade
pickerItem.id = value.id
pickerArr.append(pickerItem)
}
} else if pickerType == .teacher {
for value in self.arrTeachers {
let pickerItem:PickerItem = PickerItem()
pickerItem.title = value.teacher
pickerItem.id = value.id
pickerArr.append(pickerItem)
}
}
}
答案 0 :(得分:1)
创建一个名为PickerItemProtocol
的协议:
protocol PickerItemProtocol {
var title: String { get }
var id: String { get }
}
然后使Grade
和Teacher
符合它:
extension Grade: PickerItemProtocol {
var title: String { return grade }
}
extension Teacher : PickerItemProtocol {
var title: String { return teacher }
}
现在在prepareDataSourceForPicker
中,您可以执行以下操作:
func prepareDataSourceForPicker(pickerType:PickerType) {
let dataSource: [PickerItemProtocol]
switch pickerType {
case .grade: dataSource = self.arrGrades
case .teacher: dataSource = self.arrTeachers
}
let pickerArr = dataSource.map { item in
let pickerItem = PickerItem()
pickerItem.title = item.title
pickerItem.id = item.id
return pickerItem
}
// you might want to do something with pickerArr here...
}
答案 1 :(得分:0)
我认为最好的方法是在OOP的最基本概念中,即继承。我的意思是: