微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - 使用泛型改进类中的计算属性

如何解决Swift - 使用泛型改进类中的计算属性

我在一个视图类中有这个代码块:

private var notes: [String] = [] {
    didSet {
      if notes.count > 0,notes.count == (oldValue.count + 1) {
        tableView.insertRows(at: [IndexPath.init(row: 0,section: 3)],with: .right)
      } else {
        tableView.reloadData()
      }
    }
  }

private var images: [UIImage?] = [] {
  didSet {
    if images.count > 0,images.count == (oldValue.count + 1) {
      tableView.insertRows(at: [IndexPath.init(row: 0,section: 2)],with: .right)
    } else {
      tableView.reloadData()
    }
  }
}

private var urls: [URL?] = [] {
  didSet {
    if urls.count > 0,urls.count == (oldValue.count + 1) {
      tableView.insertRows(at: [IndexPath.init(row: 0,section: 1)],with: .right)
    } else {
      tableView.reloadData()
    }
  }
}

它工作得非常好,但我看到了这一点,我立刻想改进它,因为它几乎完全相同的东西三次......我在 Java 中使用了一些泛型,并且我已经阅读了泛型的文档斯威夫特,但我不能让它工作。我想最终做一些像

private var items: [T] = [] {
  didSet {
    if items.count > 0,items.count == (oldValue.count + 1) {
      tableView.insertRows(at: [IndexPath.init(row: 0,with: .right)
    } else {
      tableView.reloadData()
    }
  }
}

这样我就可以将所有内容都放在一个部分中。这可能吗?我仍然是新手,所以即使这对您来说是一个简单的问题,我也非常感谢您的帮助:)

谢谢!

解决方法

你可以用一个简单的函数来解决这个问题

private func updateTable(count: Int,oldCount: Int,section: Int) {
    if count > 0,count == (oldCount + 1) {
        tableView.insertRows(at: [IndexPath.init(row: 0,section: section)],with: .right)
    } else {
        tableView.reloadData()
    }
}

这样可以简化代码

private var notes: [String] = [] {
    didSet {
        updateTable(count: notes.count,oldCount: oldValue.count,section: 3)
    }
}

另一种选择是传递数组

private func updateTable(array: [Element],oldArray: [Element],section: Int) {
    if array.count > 0,array.count == (oldArray.count + 1) {
        tableView.insertRows(at: [IndexPath.init(row: 0,with: .right)
    } else {
        tableView.reloadData()
    }
}
,

我认为您在这里遇到的问题是,与许多语言不同,Swift 中的 Array 类型本身就是一个泛型。你可以把数组放在一个包装结构中,在 T 上泛型,这将允许你实现 setter。

struct MyArray<T> {
   var items: [T] = [] {
      didSet {
         if items.count > 0,items.count == (oldValue.count + 1) {
            //something
         } else {
            //something else
         }
      }
   }
}

然后,如果您愿意,可以包装所有常用方法,或者编写一个 Iterator 并符合 Sequence 以获取所有默认方法。 这是否值得处理包装器的开销我会留给你;-)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。