Reputation:
I try to implement a sample function to return a function.
The intended code in JS is as follows:
var class1 = function(val)
{
var val1 = val;
var obj = {
say: function(val)
{
console.log(val1 + ' ' + val);
}
};
return obj;
};
var obj1 = class1('hello');
obj1.say('ken');
obj1.say('tom');
In Swift, the function is a first-class object, but sort of hard to write like in JS. Thanks!
Upvotes: 4
Views: 15215
Reputation: 9136
If you want to replicate your Javascript code in Swift, it will be sort of like the following:
struct Class1 {
let val1: String
init(_ val1: String) {
self.val1 = val1
}
func say(val: String) {
print(val1 + " " + val)
}
}
let class1: (String) -> Class1 = { val1 in
let obj = Class1(val1)
return obj
}
let obj1 = class1("hello")
obj1.say("ken")
obj1.say("tom")
Where class1 variable holds a function to be invoked which accepts a String as parameter and returns an object of Class1 type.
Tweaking a litle bit the solution of Jean-Philippe Pellet, in order to make it more clear hopefully:
typealias ReturnType = (String) -> ()
func class1(val: String) -> ReturnType {
let returnFunction: ReturnType = { (val1: String) in
print(val + " " + val1)
}
return returnFunction
}
let obj1 = class1("hello")
obj1("ken")
obj1("tom")
where the typealias ReturnType represents the signature of a function which accepts a String and returns void.
Upvotes: 1
Reputation: 59994
Here it is, a bit tweaked:
func mkGreeter(greeting: String) -> (String) -> () {
return { name in println("\(greeting) \(name)") }
}
let greeter = mkGreeter("Hello")
greeter("Ken") // prints "Hello Ken"
greeter("Tom") // prints "Hello Tom"
mkGreeter
returns a function which “remembers” the greeting
param and which can be called directly.
Upvotes: 6