Reputation: 53112
So, when declaring a closure, we can get pretty abstract. For example, we could do a sort with an inline closure like:
var arr = sort(["a", "b", "c"], { $0 > $1 }) // Shows ["c", "b", "a"]
arr
Which could then be simplified to an operator function like this:
var arr = sort(["a", "b", "c"], >) // Shows ["c", "b", "a"]
arr
Because:
Swift’s String type defines its string-specific implementation of the greater-than operator (>) as a function that has two parameters of type String, and returns a value of type Bool. This exactly matches the function type needed for the sort function’s second parameter. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation
However, I can't seem to find a way to do this outside of the context of that argument. When it's being passed as an argument, '>' is almost like the name of a function that is associated with 'String'. In that way, I would think it should be possible to assign outside the context of the argument. For example, is there some way I could do this:
var inlineClosure: (String, String) -> Bool = { > }
// or
var inlineClosure: (String, String) -> Bool = >
This is purely experimental, I am just curious if it is possible.
This question isn't about how to assign an inline closure in any way other than as an operator. I'm already familiar with various declaration types, including shorthand arguments & trailing closures. I'm specifically looking for a way to do this by only assigning an operator.
Upvotes: 4
Views: 1082
Reputation: 70135
Assign inlineClosure
with an actual closure with:
7> var inlineClosure = { (a:String, b:String) -> Bool in return a > b }
inlineClosure: (String, String) -> Bool =
8> inlineClosure ("a", "b")
$R3: Bool = false
9> inlineClosure ("c", "b")
$R4: Bool = true
BTW, there is special syntax for a method that has a closure as the last argument:
var answer = sort ([1,3,2]) { (a:Int, b:Int) -> Bool in return a < b }
Convenient that.
Upvotes: 0
Reputation: 2242
Like this?
var inlineClosure: (String, String) -> Bool = { $0 > $1 }
Upvotes: 0
Reputation: 64644
This seems to be a bug with Xcode. You can get it to work though. Type out the whole line like you did:
var inlineClosure: (String, String) -> Bool = { > }
Then delete and retype the operator. For some reason that allows the parser to understand what you're trying to do.
Upvotes: 0