-1

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

2 回答 2

0

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

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
于 2021-03-17T10:36:12.360 回答
0

在 Playground 上测试运行

选项 1:使用 Dictionary 检查

func convertToDictionary(json: String) -> [String: Any]? {
    if let data = json.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

func getNonEmptyCount(dict: [String: Any]?) -> Int {
    return dict?.filter({
        if let value = $0.value as? String {
            return !value.isEmpty
        } else if let value = $0.value as? Int {
            return value > 0
        } else {
            return false
        }
    }).count ?? 0
}

let json = """
{
     "postID": 325,
     "postName": "Test1",
     "postDetail": "Test1",
     "postDesc": "",
}
"""
getNonEmptyCount(dict: convertToDictionary(json: json))

选项 2:使用镜像检查

let json = """
{
     "postID": 325,
     "postName": "Test1",
     "postDetail": "Test1",
     "postDesc": "",
}
"""

func getNonEmptyCount(json: String) -> Int {
    let model = try! JSONDecoder().decode(Post.self, from: json.data(using: .utf8)!)
    let mirror = Mirror(reflecting: model)
    return mirror.children.filter {
        if let value = $0.value as? String {
            return !value.isEmpty
        } else if let value = $0.value as? Int {
            return value > 0
        } else {
            return false
        }
    }.count
}

print(getNonEmptyCount(json: json))
于 2021-03-17T08:15:28.350 回答