【问题标题】:Swift count non empty instances in struct快速计算结构中的非空实例
【发布时间】:2021-03-17 08:00:01
【问题描述】:

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

【问题讨论】:

  • 您的属性也可以是nil。当它们为 nil 时,您想将它们计为非空字符串吗?还是您一开始就不想让它们成为可选项?
  • 跟进上一个问题,第一个是整数。什么被认为是空整数,nil 或 0 或两者兼而有之?
  • @Sweeper 是的。我想将 nil 算作一个非空字符串。因为我想在 tableview 中显示它。
  • @JoakimDanielson nil 可以。
  • 是什么阻止你编写一个简单的函数来执行每个属性的验证并返回计数?

标签: swift swift-structs


【解决方案1】:

在 Playground 上测试运行

选项 1:使用字典检查

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))

【讨论】:

  • 由于用户正在使用 Codable 并且已经解析了 JSON,返回到 JSONData (JSONEncoder),然后返回到 Dictionary (JSONSerialization),进行计数可能比枚举结构的值过大并检查它们。
  • 另外,由于 OP 对如何计算 nil 值有奇怪的要求,我不确定这是否可以正常工作(请参阅问题的 cmets)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多