3

Is it possible to map an array with a function that takes in two arguments? Something like this:

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
  • Unless amount and interestRate will both have the same value, your example is not gonna work. Of course with an array of tuples for instance it could easily work. Commented Dec 15, 2017 at 21:57
  • What are the values in arr? Are they the amounts? You could use map with a fixed rate and the amount from the array Commented Dec 15, 2017 at 22:01

2 Answers 2

4

If you want to pass the same interest rate to all values, you can do:

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)

Output:

[amount: 2, rate: 0.04, amount: 5, rate: 0.04, amount: 1, rate: 0.04, amount: 4, rate: 0.04, amount: 8, rate: 0.04, amount: 4, rate: 0.04]

If you want each to have their own, you can do it with tuples:

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)

Output:

[amount: 2, rate: 0.04, amount: 5, rate: 0.07, amount: 1, rate: 0.1, amount: 4, rate: 0.035, amount: 8, rate: 0.25, amount: 4, rate: 0.2]

And thanks to Martin R, the 2nd example can be shorted a bit as:

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)
Sign up to request clarification or add additional context in comments.

3 Comments

The code in my answer is copied directly from an Xcode 9.2 playground and it gives me no errors.
The code in your question doesn't compile as-is so make sure you copy the code from my answer.
Or let bankRateArr2 = arr2.map(BankRate.init) if arr2 is defined as [(Int, Float)]
2

Assuming that you will have two separate arrays

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

you could use

let bankRates = zip(amounts, rates).map(BankRate.init)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.