使用带有两个参数的函数映射数组 - Swift

时间:2017-12-15 21:53:28

标签: arrays swift

是否可以使用带有两个参数的函数映射数组? 像这样:

let arr = [2,5,1,4,8,4]
let bankRateArr = arr.map(BankRate.init(amount:interestRate:))

class BankRate {
    let amount: Int
    let interestRate: Float

    init(amount: Int, interestRate: Float) {
        self.amount = amount
        self.interestRate = interestRate
    }
}

2 个答案:

答案 0 :(得分:2)

如果您想将相同的利率传递给所有值,您可以这样做:

class BankRate: CustomStringConvertible {
    let amount: Int
    let interestRate: Float
    init(amount: Int, interestRate: Float){
        self.amount = amount
        self.interestRate = interestRate
    }

    var description: String {
        return "amount: \(amount), rate: \(interestRate)"
    }
}

let arr = [2, 5, 1, 4, 8, 4]
let bankRateArr = arr.map { BankRate(amount: $0, interestRate: 0.04) }
print(bankRateArr)

输出:

  

[金额:2,费率:0.04,金额:5,费率:0.04,金额:1,费率:0.04,金额:4,费率:0.04,金额:8,费率:0.04,金额:4,费率: 0.04]

如果你想让每个人都有自己的,你可以用元组来做:

let arr2 = [(2, 0.04), (5, 0.07), (1, 0.1), (4, 0.035), (8, 0.25), (4, 0.2)]
let bankRateArr2 = arr2.map { BankRate(amount: $0.0, interestRate: Float($0.1)) }
print(bankRateArr2)

输出:

  

[金额:2,费率:0.04,金额:5,费率:0.07,金额:1,费率:0.1,金额:4,费率:0.035,金额:8,费率:0.25,金额:4,费率: 0.2]

感谢Martin R,第二个例子可以缩短为:

let arr3: [(Int, Float)] = [(2, 0.04), (5, 0.07), (1, 0.1), (4, 0.035), (8, 0.25), (4, 0.2)]
let bankRateArr3 = arr3.map(BankRate.init)
print(bankRateArr3)

答案 1 :(得分:0)

假设您将有两个独立的数组

"b.h"

你可以使用

let amounts = [2, 5, 1, 4 ,8 ,4]
let rates: [Float] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]