Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between functions and methods in Swift?

I always thought functions and methods were the same, until I was learning Swift through the "Swift Programming Language" eBook. I found out that I cannot use greet("John", "Tuesday") to call a function that I declared inside a class, as shown in the eBook in the screen shot below:

function declaration in swift

I received a error saying that "Missing argument label 'day:' in call" as per this screen shot:

Error message in swift

Here is the code:-

import Foundation import UIKit  class ViewController2: UIViewController {     override func viewDidLoad() {         super.viewDidLoad()          //var dailyStatement = greet("John", "Tuesday")         var dailyStatement = greet("John", day: "Tuesday")         println(dailyStatement)     }      func greet(name: String, day: String) -> String {         return "Hello \(name), today is \(day)."     } } 

After some research, I found this post: Difference between a method and a function, and it seems to me that the function that I declared inside a class is actually called a method. So, the syntax that I use to call the method is different compared to the syntax that I use to call a function.

I never realized this difference when I was programming in Objective-C.

  1. What are the differences between functions and methods in Swift?

  2. When do we use functions and when do we use methods in Swift?

like image 654
Ricky Avatar asked Jun 10 '14 05:06

Ricky


People also ask

What is the difference between the functions and methods?

Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again.

What are methods in Swift?

Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type.

What is the difference between functions and closures in Swift?

Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.

Should I use method or function?

Here's a simple rule of thumb: if the code acts upon a single instance of an object, use a method. Even better: use a method unless there is a compelling reason to write it as a function. Don't over think it.


2 Answers

After a few hours of reading and experimenting, here are the things that I found out:-

Functions in Swift

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.

Resource: Official Apple Documentation on Functions in Swift

Function Parameter Names

However, these parameter names are only used within the body of the function itself, and cannot be used when calling the function. These kinds of parameter names are known as local parameter names, because they are only available for use within the function’s body.

It means that by default, all the parameters for Function are local parameters.

But, sometimes we want to indicate the purpose of each parameter. So, we can actually define an external parameter name for each parameter. Example Code:

func someFunction(externalParameterName localParameterName: Int) {     // function body goes here, and can use localParameterName     // to refer to the argument value for that parameter } 

Another way to make the external parameter name is using hash symbol (#) to shorten the name.

func someFunction(#localParameterName: Int) {     // function body goes here, and can use localParameterName     // to refer to the argument value for that parameter } 

To call the above functions with external parameter, you may use

someFunction(localParameterName:10) 

Methods in Swift

Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type.

Resource: Official Apple Documentation on Methods in Swift

However, the default behavior of local names and external names is different for functions and methods.

Specifically, Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default.

Code below shows the differences for default and non-default parameters for method in Swift.

import Foundation import UIKit  class ViewController2: UIViewController {     override func viewDidLoad() {         super.viewDidLoad()          //Default methods calling         var dailyStatement = greet("Rick", day: "Tuesday")         println(dailyStatement)          //First parameter is also an external parameter         var dailyStatement2 = greet2(name:"John", day: "Sunday")         println(dailyStatement2)     }      //Default: First Parameter is the local parameter, the rest are external parameters     func greet (name: String, day: String) -> String {         return "Hello \(name), today is \(day)."     }      //Use Hash symbol to make the First parameter as external parameter     func greet2 (#name: String, day: String) -> String {         return "Hello \(name), today is \(day)."     } } 

I might miss some important details. Hope someone can provide a better answer.

like image 97
Ricky Avatar answered Sep 22 '22 09:09

Ricky


As you said yourself, methods are functions, but in a class. In objective-c you never realized this, because we were only coding in classes. Every function that we wrote was a method of a class (ViewController or some other class we created).

In Swift we have the ability to create functions that are not inside some class. The main reason for doing this is to write functions that are not tied to any class, and can be used wherever we need them. So if you have a function that is related to a class you write it inside the class and you can access is from every instance of the class:

class Square {    var length: Double    func area() -> Double {       return length * length    } } 

But if you need to access the function from everywhere, then you don't write it inside a class. For example:

func squared(number: Int) -> Int {     return number * number } 

About your syntax issues between functions and methods: You guessed it right, methods and functions are called a little bit differently. That is because in Objective-C we had long method names and we liked them because we could read what the methods were doing and what the parameters were for. So the first parameter in a method is in most cases described by the function name itself. And the other parameters shouldn't only be some numbers or strings or instances, they should be described as well, so Swift writes the name of the variable automatically. If you want to describe it by yourself you can do that as well:

class Something {     func desc(firstString string1: String, secondString string2:String) {...} } 
like image 28
Ben Avatar answered Sep 19 '22 09:09

Ben