首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >消除数组.sorted错误Swift 5

消除数组.sorted错误Swift 5
EN

Stack Overflow用户
提问于 2022-10-04 23:41:14
回答 2查看 114关注 0票数 0

我有一系列的章节和单元。

var chaptersAndUnits: [String] = ["Chapter 2", "Chapter 3", "Chapter 5", "Unit 12", "Chapter 40"]

我正在将它们加载到一个UIPickerView中,所以我用chaptersAndUnits = chaptersAndUnits.sorted()订购它们。

但是,在这个过程之后,我得到了一个不稳定的值:["Chapter 2", "Chapter 3", "Chapter 40", "Chapter 5", "Unit 12"]

我想消除的是Chapter 40是插入在Chapter 3之后的。这也发生在像Chapter 22这样的值中,它将在Chapter 1之后插入它。

要删除这些错误,我需要做些什么?我研究过正则表达式,但无法使它们工作。

我怎么写我自己的分类器来解决这个问题呢?

蒂娅!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-05 00:36:28

这是预期的行为。您将字符串(而不是数字)与"Chapter 40" > "Chapter 5" == true按字母顺序进行比较,它们是字符串中相同位置的字符。

如果希望将数据保留为字符串,并按所需的方式排序,则需要自定义排序函数。根据示例字符串,您可以使用以下内容

代码语言:javascript
复制
func bookLessThan(_ lhs: String, _ rhs: String) -> Bool {
   let lhsComponents = lhs.components(separatedBy: " ")
   let rhsComponents = rhs.components(separatedBy: " ")
   return lhsComponents.first! != rhsComponents.first! ? lhsComponents.first! < rhsComponents.first! :
   Int(lhsComponents.last!)! < Int(rhsComponents.last!)!
}

var chaptersAndUnits: [String] = ["Chapter 2", "Chapter 3", "Chapter 5", "Unit 12", "Chapter 40"]

let sorted = chaptersAndUnits.sorted(by: bookLessThan)

print(sorted)
// ["Chapter 2", "Chapter 3", "Chapter 5", "Chapter 40", "Unit 12"]

注意:在实践中,您可能希望安全地展开所有选项,以防您的字符串不是所有预期的格式,然后处理,可能通过返回一个假值,使它们都在末尾。

票数 1
EN

Stack Overflow用户

发布于 2022-10-05 00:14:01

我建议使用一个结构来保存它的类型(Chapters vs Units),并保存这个数字。这将使您的.sorted()方法能够正确地对其进行排序。

要理解你的“变幻莫测”的价值,这并不是所有的不稳定。它是按字母顺序排列你的字符串,这是有意义的。从技术上讲,“第40章”在“第5章”之前,因为"4“< "5”。我们可以通过使用如下的结构来修复这个问题:

代码语言:javascript
复制
struct Section: Comparable {
var type: String! //Could also make this an enum with 2 values: .chapter and .unit.
var sectionNumber: Int!

//This is the function that is called every time a "<" operator is used on two Section objects.
//if the left hand side's sectionNumber (lhs) is less than the right hand side's, then we return "true"
static func < (lhs: Section, rhs: Section) -> Bool {
    return lhs.sectionNumber < rhs.sectionNumber
}

//Same thing, but greater than.
static func > (lhs: Section, rhs: Section) -> Bool {
    return lhs.sectionNumber > rhs.sectionNumber
}
}

现在,我们可以运行.sorted(),因为记住,排序算法所依赖的只是一个数字大于另一个数字,所以我们通过实现我们自己的>和<符号。

代码语言:javascript
复制
var arr = [Section(type: "Chapter", sectionNumber: 5), 
Section(type: "Chapter", sectionNumber: 1),
Section(type: "Chapter", sectionNumber: 8),
Section(type: "Chapter", sectionNumber: 10),
Section(type: "Chapter", sectionNumber: 1),
Section(type: "Chapter", sectionNumber: 9),
Section(type: "Unit", sectionNumber: 2)]
arr = arr.sorted()

(这都是假设Unit和章节是一样的,不确定这是否是真的)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73954632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档