swift - 将公共函数的实现隐藏在私有函数中是否有任何性能优势或编译时间改进
问题描述
例如说我有一个 CarModel
struct CarModel: Codable {
var numberPlate: String
var vin: String
var model: String
var fuel: Double
var position: Position
}
我有一个公共方法
extension CarModel {
var fuelString: String {
return fuelStringImplementation
}
}
但是我没有在公共方法中实现,而是将其隐藏在私有方法后面。
private extension CarModel {
var fuelStringImplementation: String {
if fuel == 0.0 {
return "car_list_item_tank_empty".localizedString()
}
let fuelDouble = fuel*100
let finalString = String(format: "car_list_item_tank_status".localizedString(), fuelDouble)
return finalString
}
}
而对于 cellForAtIndexPath 我可以将实现隐藏在这样的私有方法中
private func collectionViewImplementation(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MainImageCollectionViewCell.className, for: indexPath)
guard let model = viewModel.modelForIndex(index: indexPath.row) else {
assertionFailure("model is nil")
return cell
}
guard let mainImageCell = cell as? MainImageCollectionViewCell else {
assertionFailure("cell is not type MainImageCollectionViewCell")
return cell
}
mainImageCell.fill(with: model)
return mainImageCell
}
解决方案
不,为了性能优势,方法是私有的还是公共的都没有关系。如果我们谈论函数和性能改进(更不用说该函数的主体实现),我们应该更接近方法调度类型。其中有一些:动态、表格和直接。例如,直接具有最佳性能。这是一个巨大的主题,所以我建议你在网上阅读一些关于它的文章。像这样,例如https://developer.apple.com/swift/blog/?id=27。
推荐阅读
- ios - iOS 错误:检测到堆损坏,空闲列表已损坏且保护值不正确:0
- python - AttributeError: 'list' 对象在尝试围绕 assertEquals 进行包装时没有属性 '_getAssertEqualityFunc'
- angular - Angular 升级后 E2E 打字稿测试没有被转译
- shell - 根据shell脚本中的特殊字符从变量中提取子字符串
- angular - 使用angular2更改html中的值
- c - 管道输入到 getchar() 提示 c
- prolog - 带分解的 Prolog 练习
- imagemagick - ImageMagick - 部分伽玛校正
- javascript - 获取下拉菜单值的日期时间并将其与文本框日期时间一起添加
- c# - 使用正则表达式验证 SQL 查询