首页 > 解决方案 > 快速计算结构中的非空实例

问题描述

我试图计算结构中非空字符串的数量以在 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": "",
}

标签: swiftswift-structs

解决方案


这听起来像是一件奇怪的事情。

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

推荐阅读