Daniel
Daniel

Reputation: 3868

Chaining methods in Swift

I'd like to write a function that I can chain to map { } functions. For example:

let arr = [1,2,3,4,5]
let list = arr.map { $0 * 2 }.applyRuleToSubtractVal(1) // return [1,3,5,7,9]

How do I define applyRuleToSubtractVal() above? (I want to do more complex things and don't want to do them inside the map.)

Upvotes: 0

Views: 1235

Answers (3)

vikingosegundo
vikingosegundo

Reputation: 52227

sketchyTech's answer is correct, but actually it is just hiding the fact, that

let list = arr.map { $0 * 2 }.map { $0 - 1 }

is executed — this is not optimal as the array is enumerated twice.

You could achieve the same with one enumeration with

let complexClosure = { (i: Int) in
    return i-1
}
let list = arr.map { complexClosure($0 * 2) }

Upvotes: 3

sketchyTech
sketchyTech

Reputation: 5906

Your map returns an array of Int so you can apply any Array method that can be performed upon an Array<Int> using dot syntax. In order to include your own methods make sure that you extend Array in a way that makes this possible, e.g.

extension Array where Element:IntegerType {
    func applyRuleToSubtractValue(num:Int) -> Array {
        return self.map{$0 - 1}
    }
}

let arr = [1,2,3,4,5]
let list = arr.map{$0 * 2}.applyRuleToSubtractValue(1) // [1, 3, 5, 7, 9]

If we didn't use protocol restrictions here then we wouldn't be able to perform a minus 1 operation, because it might be an array of any type.

Upvotes: 2

Strat Aguilar
Strat Aguilar

Reputation: 828

You need to extend the Array's functionality. The dot operator calls methods of the class or struct. Extend your own functionality to the Array struct.

Upvotes: 0

Related Questions