Reputation: 1737
When reading Custom operators about RxSwift, I noticed this func which has two parameter definitions.
func myMap<E, R>(transform: E -> R)(source: Observable<E>) -> Observable<R> {
return create { observer in
let subscription = source.subscribe { e in
switch e {
case .Next(let value):
let result = transform(value)
observer.on(.Next(result))
case .Error(let error):
observer.on(.Error(error))
case .Completed:
observer.on(.Completed)
}
}
return subscription
}
}
I have nerver seen this grammar before. I even don't know how to google it. I will appreciate it if you can give me some official doc link.
Upvotes: 4
Views: 469
Reputation: 7906
As mentioned in the comments this would be referred to as Curried Functions
.
Basically it gives you the ability to dynamically create functions with more specificity than a function would have if you sent in all the params.
Example time (this is a rather dumb example but it should give you an idea of what currying does)
func addNumbers(a a: Int, b: Int) -> Int {
return a + b
}
func addNumbers(a a: Int)(b: Int) -> Int {
return a + b
}
//usage normal function
var two = addNumbers(a:1, b:1)
var three = addNumbers(a:1, b:2)
var four = addNumbers(a:1, b:3)
//usage curried function
var addOne = addNumbers(a:1)
var two = addOne(b:1)
var three = addOne(b:2)
var four = addOne(b:3)
So if you have some problem that you know will be solved with one value for one of your params in some specific case but another value in another situation you can save yourself from sending in those parameters and instead just create the function where it will be used.
Again as I wrote above this was a dumb example but it can be very useful when writing a REST api as an example. Where you have the same functions applied to a lot of different types which can be saved in the same general way.
Another usage example Logger implemented with Currying
In your example the function for mapping objects can be applied first and then the created mapping function can be applied to the sources that should be mapped.
You can read more about it here and here
Upvotes: 3