如何在自己创建的模型类中使用泛型?
我有一个FeatureListModel类,另一个有FavoriteModel类。两者存储相同的属性,唯一的区别是不同的类模型名称。
我需要在ProductDetail控制器中显示模型属性值。
我如何使用泛型来管理这些东西呢?
这是我的代码(Swift 4.2):
第一个型号: FavoriteListModel
class FavoriteListModel {
var categoryID: Int?
var item_name: String?
var MRP: String?
}第二种型号: FeatureListModel
class FeatureListModel {
var categoryID: Int?
var item_name: String?
var MRP: String?
}我还有8-10个属性,但这只是我代码中的一些东西。
控制器- ProductDetailTableViewController
class ProductDetailTableViewController : UITableViewController {
var productDetails: FavoriteListModel!
var productFeatureList: FeatureListModel!
fileprivate func displayProduct() {
if productDetails != nil {
title = productDetails.item_name
categoryID = productDetails.categoryID!
}else if productFeatureList != nil {
categoryID = productFeatureList.categoryID!
title = productFeatureList.item_name
}
}在我的Product Detail Table Controller中,我正在访问模型对象并在屏幕上显示。我不想要if-else检查。
发布于 2018-07-14 16:17:19
你混淆了泛型和协议。在您的情况下,协议更可取。
在ProductDetailTableViewController中有一个对象,它响应item_name (顺便说一句,请遵守camelCased命名约定itemName)和categoryID的getter方法。对象的类型以及其他属性和函数的存在并不重要。
创建协议
protocol Listable {
var itemName : String { get }
var categoryID : Int { get }
}然后在您的类中采用该协议(您真的需要一个类吗?)并且至少将categoryID声明为非可选的,因为您无论如何都要在以后强制解开该值。不要使用可选参数作为不编写初始化器的借口。
class FavoriteListModel : Listable { ...
class FeatureListModel : Listable { ...在ProductDetailTableViewController中,不是两个属性,而是一个属性声明为Listable,并且使用可选的绑定代替objective-c-ish的nil检查:
var details: Listable!
fileprivate func displayProduct() {
if let productDetails = details {
title = productDetails.itemName
categoryID = productDetails.categoryID
}
}发布于 2018-07-14 15:58:07
您在这里拥有的不是泛型的用例。例如,当你有一个函数做完全相同的事情,但可以与两种不同的参数类型一起使用时,就会使用泛型。这就是你使用泛型的时候。
另一个概念是超类(父类或基类),当你有一个具有公共属性的类,然后是具有这些属性的其他类,然后是额外的和不同的唯一属性,在这种情况下,每个类都是父类的子类。
你这里有的都不是他们。对于这种情况,一个好的体系结构是只有一个模型类型(类或结构),并在视图控制器中使用两个不同的集合(数组或集合)。
您还可以创建一个收藏的类或特色类,其中包含一个包含模型的数组。
https://stackoverflow.com/questions/51336230
复制相似问题