5

In Swift headers, the isSeparator: argument accepts a closure

public func split(maxSplit: Int = default, allowEmptySlices: Bool = default, @noescape isSeparator: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.SubSequence] 

But in the documentation, it lists closure syntax differently

{ (parameters) -> return type in statements } 

How are you supposed to know that (Self.Generator.Element) throws -> Bool rethrows refers to a closure / requires a closure? Are there other ways that the headers/docs might list argument as meaning a closure?

2
  • In a header (parameters) -> return type within the parentheses of a function is always a closure. Commented Jan 7, 2016 at 22:36
  • Possible duplicate of How to read swift headers Commented Jan 7, 2016 at 23:35

3 Answers 3

7

The "thing" giving away that this is a closure is the ->. The full type is

(Self.Generator.Element) throws -> Bool 

It means that the closure takes a variable of type Self.Generator.Element and has to return a Bool upon some calculation based on the input. It may additionally throw some error while doing so - that is what the throws is for.

What you then write

{ (parameters) -> return type in statements } 

would be an actual implementation, a value of some generic closure type.

The type of a closure is for example (someInt:Int, someDouble:Double) -> String:

var a : ((someInt:Int, someDouble:Double) -> String) 

Once again the thing giving away that a is actually a closure is the -> in the type declaration.

Then you assign something to a via some code snippet following your second code block:

a = { (integer, floating) -> String in return "\(integer) \(floating)" } 
Sign up to request clarification or add additional context in comments.

Comments

3

You can tell by the argument's type. Everything in Swift has a type, including functions and closures.

For example, this function...

func add(a: Int, to b: Int) -> Int { return a + b } 

...has type (Int, Int) -> Int. (It takes two Ints as parameters, and returns an Int.)

And this closure...

let identity: Int -> Int = { $0 } 

...has type Int -> Int.

Every function and closure has a type, and in the type signature there is always a -> that separates the parameters from the return value. So anytime you see a parameter (like isSeparator) that has a -> in it, you know that the parameter expects a closure.

Comments

2

the isSeparator definition means (Self.Generator.Element) throws -> Bool that you will be given an Element and you should return a Bool. When you will call split, you then can do the following :

 [1,2,3].split(…, isSeparator : { element -> Bool in return false }) 

This is a pure silly example but that illustrates the second part of your question

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.