【问题标题】:How to use generics in own created model class in iOS?如何在 iOS 中自己创建的模型类中使用泛型?
【发布时间】:2018-08-03 00:49:58
【问题描述】:

如何在自己创建的模型类中使用泛型?
我有一个 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

  }
}

在我的产品详细信息表控制器中,我正在访问模型对象并显示在屏幕上。 我不想要 if-else 检查。

【问题讨论】:

  • 请出示您的代码。
  • 你可以为两者保留一个模型类!
  • @luk2302:我已经更新了我的问题。
  • @Lion:谢谢!!但是我怎么能在泛型中使用呢?
  • 泛型是什么意思?

标签: ios swift generics


【解决方案1】:

您正在混淆泛型和协议。在您的情况下,协议更可取。

ProductDetailTableViewController 中有一个对象响应item_name 的getter(顺便请遵守camelCased 命名约定itemName)和categoryID。对象的类型以及是否存在其他属性和功能并不重要。

创建协议

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
   }
}

【讨论】:

    【解决方案2】:

    您在这里所拥有的不是泛型的用例。例如,当您有一个功能完全相同但可以与两种不同的参数类型一起使用时,就会使用泛型。那是你使用泛型的时候。

    另一个概念是超类(父类或基类),当您有一个具有公共属性的类,然后是具有这些属性的其他类,然后是额外的和不同的独特属性时使用它,在这种情况下,每个类都是父类的子类类。

    你在这里所拥有的都不是。对于这种情况,一个好的架构只是一个模型类型(类或结构)并在视图控制器中使用两个不同的集合(数组或集合)。

    您还可以创建一个收藏类或特色类,其中包含您的模型的数组。

    【讨论】:

    • 是的,我知道。我可以通过使用单个模型来解决我的问题。但我的问题与泛型有关。
    • 你不能,泛型用于不同的类型而不是不同的名称。
    猜你喜欢
    • 2016-06-20
    • 1970-01-01
    • 2014-09-12
    • 2019-12-14
    • 2022-01-21
    • 2019-09-30
    • 2018-11-01
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多