Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift `in` keyword meaning?

Tags:

ios

keyword

swift

I am trying to implement some code from parse.com and I notice a keyword in after the void.

I am stumped what is this ? The second line you see the Void in

PFUser.logInWithUsernameInBackground("myname", password:"mypass") {   (user: PFUser?, error: NSError?) -> Void in   if user != nil {     // Do stuff after successful login.   } else {     // The login failed. Check error to see why.   } } 

The docs don't document this. I know the in keyword is used in for loops.

Anyone confirm?

like image 422
Martin Avatar asked May 21 '15 16:05

Martin


People also ask

What is where in Swift?

You use where in Swift to filter things, kinda like a conditional. In various places throughout Swift, the “where” clause provides a constraint and a clear indicator of the data or types you want to work with. What's so special about where – as you'll soon see – is its flexible syntax.

What does _: mean in Swift documentation?

The underscore indicates that there is no external parameter name for the function. Apple's Swift Documentation talks about this concept in terms of when you're writing your own functions.

What is a Swift closure?

In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World .

Is type a reserved word in Swift?

Keywords reserved in particular contexts: associativity , convenience , didSet , dynamic , final , get , indirect , infix , lazy , left , mutating , none , nonmutating , optional , override , postfix , precedence , prefix , Protocol , required , right , set , some , Type , unowned , weak , and willSet .


2 Answers

In a named function, we declare the parameters and return type in the func declaration line.

func say(s:String)->() {     // body } 

In an anonymous function, there is no func declaration line - it's anonymous! So we do it with an in line at the start of the body instead.

{     (s:String)->() in     // body } 

(That is the full form of an anonymous function. But then Swift has a series of rules allowing the return type, the parameter types, and even the parameter names and the whole in line to be omitted under certain circumstances.)

like image 156
matt Avatar answered Oct 08 '22 22:10

matt


Closure expression syntax has the following general form:

Closure Expression Syntax

like image 31
Artem Zaytsev Avatar answered Oct 08 '22 22:10

Artem Zaytsev