如何在swift中对字符串数字数组进行排序?

问题描述 投票:0回答:1

我正在尝试对与其他三个数组映射的数组进行排序。 我的主数组是字符串+数字 i e ["Day 1","Day 2","Day 3"...] 其他三个数组也是字符串数组。

现在我正在使用以下代码。

var mainDayArray = ["Day 1","Day 2","Day 3","Day 4","Day 5","Day 6","Day 7","Day 8","Day 9","Day 10","Day 11","Day 12","Day 13"]

var timeArray = ["06:09 PM", "06:09 PM", "06:08 PM", "06:08 PM", "06:08 PM", "06:07 PM", "06:07 PM", "06:07 PM", "06:07 PM", "06:06 PM", "06:06 PM", "06:06 PM", "06:06 PM"]

var dateArray = ["Oct 1", "Oct 2", "Oct 3", "Oct 4", "Oct 5", "Oct 7", "Oct 4", "Oct 5", "Oct 9", "Nov 2", "Nov 3", "Nov 4", "Nov 01"]

var studentNameArray =["as","ab","vf","sd","fd","gr","ht","jh","kl","mn","sf","ts","at"]


let offsets = mainDayArray.enumerated().sorted { $0.element > $1.element }.map { $0.offset }

let sortedCompletedDayArray = offsets.map { mainDayArray[$0] }
                    let sortedCompletedDateArray = offsets.map { dateArray[$0] }
                    let sortedCompletedTimeArray = offsets.map { timeArray[$0] }
                    let sortedCompletedStudentNamesArray = offsets.map { studentNameArray[$0] }

但是我在这里得到了错误的数据。我得到的输出如下,

maindayArray = ["第 9 天","第 8 天","第 7 天","第 6 天","第 5 天","第 4 天","第 3 天","第 2 天","第 13 天","第 12 天”、“第 11 天”、“第 1 天”]

arrays swift sorting
1个回答
0
投票

您的日期数组看起来已经排序,但以防万一您的日期数组可能未排序,这是我的解决方案:

var mainDayArray = ["Day 1","Day 2","Day 3","Day 4","Day 5","Day 6","Day 7","Day 8","Day 9","Day 10","Day 11","Day 12","Day 13"]

var timeArray = ["06:09 PM", "06:09 PM", "06:08 PM", "06:08 PM", "06:08 PM", "06:07 PM", "06:07 PM", "06:07 PM", "06:07 PM", "06:06 PM", "06:06 PM", "06:06 PM", "06:06 PM"]

var dateArray = ["Oct 1", "Oct 2", "Oct 3", "Oct 4", "Oct 5", "Oct 7", "Oct 4", "Oct 5", "Oct 9", "Nov 2", "Nov 3", "Nov 4", "Nov 01"]

var studentNameArray = ["as","ab","vf","sd","fd","gr","ht","jh","kl","mn","sf","ts","at"]


let offsets = mainDayArray.map(parseNumber).enumerated().sorted { $0.element < $1.element }.map(\.offset)

let sortedCompletedDayArray = offsets.map { mainDayArray[$0] }
let sortedCompletedDateArray = offsets.map { dateArray[$0] }
let sortedCompletedTimeArray = offsets.map { timeArray[$0] }
let sortedCompletedStudentNamesArray = offsets.map { studentNameArray[$0] }

func parseNumber(from element: String) -> Int {
    Int(element.split(separator: " ").last!)!
}
© www.soinside.com 2019 - 2024. All rights reserved.