Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created June 4, 2014 01:12
Show Gist options
  • Select an option

  • Save loganwright/2c3eba97f61bfceafda1 to your computer and use it in GitHub Desktop.

Select an option

Save loganwright/2c3eba97f61bfceafda1 to your computer and use it in GitHub Desktop.
import Cocoa
/*
Basic Function - Let's jump right into it and create an extremely basic function named 'sayHello' that takes no arguments and has no return.*/
func sayHello() {
println("Hello!")
}
/*
Now to call this function we simply use it's name followed by '()'. To see the console ouput in playground, you might have to open up the side window (explain how to open window quick)
*/
sayHello()
/* ARGUMENTS
Let's add a little bit to what we have so far and create a function named 'sayHelloTo' that takes a single string argument
*/
func sayHelloTo(nameOfPerson name: String){
println("Hello, \(name)")
}
/*
You'll notice a few things about the syntax I'm using. While this is more explicit than is usually necessary in Swift, I find it aids in learning. Let's talk about the contents of the parenthetical:
(nameOfPerson name: String)
1. 'nameOfPerson' - This functions as an `externalParameter` which exposes it when writing the function. This is not necessary if the contents of the function are obvious.
2. 'name:' - This signifies an argument called 'name' that we can use within our function
3. 'String' - This means that our argument will be of type String
You would call this like so:
*/
sayHelloTo(nameOfPerson: "John")
/* RETURNS
Of course, functions can also return values. Let's make our function return a greeting from the person we said hello to */
func sayHelloTo(#name: String) -> String {
println("Hello, \(name)")
return "Well, hello to you too!"
}
/*
As you can see, it's a very civil conversation. Our function will say hello to somebody, and that person will in turn say hello back. You're probably wondering about the '#' prefix. That is used when I'd like my internal and external parameter names to be the same. It is basically shorthand for:
(name name: String)
Which the compiler will automatically suggest you should correct.
The most important part though is the addition of the arrow to indicate our return argument. The -> syntax signies the return type of the function. We're saying that this function will return a string
*/
var response = sayHelloTo(name: "Jimbo")
/*
Try making functions that take various types of arguments and modify data in various ways as practice. Next time, we'll talk about functions as arguments, variadic arguments, and how to use tuples to return multiple values
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment