gpt4 book ai didi

Swift 在特定条件下基于两个数组创建新数组

转载 作者:可可西里 更新时间:2023-11-01 01:00:02 25 4
gpt4 key购买 nike

我需要一些帮助才能在 Swift 2.0 中建立一个新数组。

我有两个数组,一个包含日期,另一个包含该日期的付款。

let year = [February 2016, March 2016, June 2017, October 2017, January 2018, April 2019] // Data at which a payment is initiated
let payment = ["1000","2000,"3000","1000","2000,"3000"] // payment amount at date in array year

我想基于此在 Swift 代码中创建两个新数组。最终结果应该是这样的:

let yearSum [2016, 2017, 2018,2019]  // only full year 
let paymentSum ["3000","4000","2000","3000"] // sum of all payment in the year

数组“yearSum”应该只包含完整的年份数字,而“paymentSum”应该包含当年所有付款的总和。

有人建议我如何编码吗?

非常感谢

最佳答案

输入

首先让我们为输入常量分配好名字

let monthStrings = ["February 2016", "March 2016", "June 2017", "October 2017", "January 2018", "April 2019"]
let paymentStrings = ["1000", "2000", "3000", "1000", "2000", "3000"]

什么地方会出错

我们正在使用字符串作为输入,因此在解析 Date 或 Int 期间可能会出错。为了清楚起见,让我们定义以下枚举

enum Error: ErrorType {
case InputParamsHaveDifferentSizes(Int, Int)
case FirstParamHasInvalidDate
case SecondParamHasInvalidInt
}

函数

func groupData(monthStrings: [String], paymentsStrings:[String]) throws -> [Int:Int] {
// make sure both arrays have the same size
guard monthStrings.count == paymentStrings.count
else { throw Error.InputParamsHaveDifferentSizes(monthStrings.count, paymentStrings.count) }

let formatter = NSDateFormatter()
formatter.dateFormat = "MMM yyyy"

// creates dates: an array of NSDate representing monthStrings
// if dates has a different size of monthsString then throws and error
guard
case let dates = (monthStrings.flatMap { formatter.dateFromString($0) })
where dates.count == monthStrings.count
else { throw Error.FirstParamHasInvalidDate }

// creates payments: an array of Int representing paymentsStrings
// if payments has a different size of paymentsStrings then throws and error
guard
case let payments = (paymentStrings.flatMap { Int($0) })
where payments.count == paymentStrings.count
else { throw Error.SecondParamHasInvalidInt }

// put togheter dates and payments and group the results by year
return zip(dates, payments).reduce([Int:Int]()) { (var result, elm) -> [Int:Int] in
let year = NSCalendar.currentCalendar().components([NSCalendarUnit.Year], fromDate: elm.0).year
result[year] = elm.1 + (result[year] ?? 0)
return result
}
}

用法

let res = try groupData(monthStrings, paymentsStrings: paymentStrings)
print(res) // [2018: 2000, 2017: 4000, 2016: 3000, 2019: 3000]

更新

在下面的评论中,您说您需要按索引访问键,并且需要将它们排序

let sortedKeys = res.keys.sort()

func value(index:Int) -> String? {
let key = sortedKeys[index]
let value = res[key]
return value
}

关于Swift 在特定条件下基于两个数组创建新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35687182/

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