swift - 快速计算结构中的非空实例
问题描述
我试图计算结构中非空字符串的数量以在 tableView 中设置 numberOfRow。""
当数据不需要在tableView中显示时,一些数据会返回给我。所以我需要根据""
结构中的非来计算numberOfRow。但我不知道该怎么做。
""
我需要在下面的 Post 结构中根据非获取行数。
struct Post : Codable {
let postID : Int?
let postName : String?
let postDetail : String?
let postDesc : String?
}
我想从下面的 JSON 数据中得到 3,因为 postDesc 是""
. 我怎么数才能得到3。
{
"postID": 325,
"postName": "Test1",
"postDetail": "Test1",
"postDesc": "",
}
解决方案
这听起来像是一件奇怪的事情。
protocol EmptyTest {
var isEmpty: Bool { get }
}
extension Optional: EmptyTest where Wrapped: EmptyTest {
var isEmpty: Bool {
switch self {
case .none:
return true
case let .some(s):
return s.isEmpty
}
}
}
extension String: EmptyTest {}
extension Post {
var nonEmptyProperties: [Any] {
Mirror(reflecting: self)
.children
.filter { $0.value is EmptyTest }
.reduce([]) { e, p in
(p.value as! EmptyTest).isEmpty == true ? e :
e + [p]
}
}
}
Post(postID: nil, postName: "name", postDetail: nil, postDesc: "Desc")
.nonEmptyProperties
.count
推荐阅读
- c# - 在 Visual Studio 2019 社区上调试无法识别用户
- java - 如何将@OneToOne 关系映射到 Hibernate 中的静态表
- excel - Excel 宏搜索和替换单元格
- mysql - 汇总以前的购买记录
- html - 如果内容由 for 循环填充,如何使行的列内容高度适合同级列高度?
- c++ - C++ Boost::Spirit 解析复杂布尔表达式并构造等效树
- c# - 如何在 Excel 中使用 C# 更改数组内容的 Font.Bold?
- javascript - 如何返回数组的所有元素,它们之间有空格?
- java - 列表视图随机更改项目
- java - Spring Security - Active Directory 获取自定义用户详细信息