Suppose I have two inits and one private property like below.
struct MyStruct {
let clousure: (Int, String, Bool) -> String
public init(clousure: @escaping (Int, String) -> String) {
/// How to assign this to the private property of MyStruct
self.clousure = ... ? /// THIS IS MY QUESTION
}
public init(clousure: @escaping (Int, String, Bool) -> String, ... ) {...}
Is there a way how can i wrap the accepted clousure and supply the bool as some default value, i.e false? thanks in advance
CodePudding user response:
If you would share more info about the goal and what you are trying to achieve by passing the clousure and/or disregard part of the arguments we can help further. From the code point of view, it seems like the @escaping closure you are passing can just disregard the boolean value as follow:
struct MyStruct {
let clousure: (Int, String, Bool) -> String
public init(clousure: @escaping (Int, String) -> String) {
/// How to assign this to the private property of MyStruct
self.clousure = { i, str, _ -> String in
return clousure(i, str)
}
}
}
And be used as follow:
let s = MyStruct() { i, s -> String in return "string = \(s), int = \(i)"}
print(s.clousure(1, "hello", false))
Resulting in the output
string = hello, int = 1
I'm not sure why would you want to do that, maybe you indeed want to achieve something like @Quack E. Duck suggested and have different outcome given the boolean value:
struct MyStruct {
let clousure: (Int, String, Bool) -> String
public init(clousure: @escaping (Int, String) -> String) {
/// How to assign this to the private property of MyStruct
self.clousure = { i, str, increaseCount -> String in
if increaseCount { return clousure(i 1, str) }
else { return clousure(i, str) }
}
}
}