gpt4 book ai didi

swift - 避免在 Swift 中的排序闭包内强制展开

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:09 24 4
gpt4 key购买 nike

我正在尝试根据可选的 Int 属性对对象数组进行排序。

// sorting each language array based on most stars
groupedDictionariesValueUnwrapped.sort(by: { $0.stars! > $1.stars! })

数组的类型是[SingleRepository],SingleRepository 有一个可选的Int。星星:Int?

我应该如何避免在排序中强制展开?

最佳答案

您正在按降序排序。

使用 nil 合并运算符 ?? 安全地展开值并将 nil 替换为 Int.min将项目放在数组的末尾:

// sorting each language array based on most stars
groupedDictionariesValueUnwrapped.sort(by: { ($0.stars ?? Int.min) > ($1.stars ?? Int.min) })

或使用?? Int.max 将它们放在开头。

关于swift - 避免在 Swift 中的排序闭包内强制展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com