Brief Introduction About Swift
Swift is a language developed by Apple which is made using modern approach, include safety features and software design patterns. As the name suggests swift is fast, safe and easy to use. It is basically made a replacement for c-based family(C, C++ and Objective-C). It can be used to make apps and can be also used for cloud services and it is among the fastest growing languages.
I will be often using the term methods as it sounds more appropriate to me
What are Functions/Methods?
Methods are block of code that can be reused any number of times. Methods consists of declaration, definition and calling. We will be doing declaration and definition at same time.
General Syntax
Method in swift is declared using func
keyword.
//Generally function looks like this
//Declaration and Definition
func function_name(parameter) -> return_type {
body
}
//Calling of function
function_name()
Note : Semicolons are optional in Swift.
Types of Methods
1.Without Parameter and Return Type
func demo() {
print("Hello, World!")
}
demo()
2.With parameters but without return type
func demo(name : String) {
print("Hello, \(name)")
}
demo("Neeraj")
3.With parameters and Return Type
func demo(name : String) -> String {
return name
}
print(demo("Neeraj"))
4.With Multiple Return Values
Above were simple but this may sound bit complicated as we return tuple when we have to return multiple value.
Now, you may ask why tuple?
The reason is very simple as tuples are very flexible and we can return multiple values of different kind in tuple.Example if we want to return a Int and String from a function for example (404, "Page not Found") an error from web page we can use tuple. Let's see it in code
func errorInPage(errorCode: Int, errorStatus: String) -> (error: Int, description: String) {
return(errorCode, errorStatus)
}
var errorReturned = errorInPage(errorCode: 404, errorStatus: "Page Not Found")
print(errorReturned)
//Output
//(error: 404, description: "Page Not Found")
Let's see a function which will return maximum and minimum value from an array passed.
//Xcode Playground
import UIKit // Exclude if not running in Xcode as UIKit is an Apple framework
func minMaxValue(array : [Int]) -> (minValue : Int, maxValue : Int) {
var maxValue = array[0]
var minValue = array[0]
for i in 1..<array.count {
if array[i] > maxValue {
maxValue = array[i]
}
if array[i] < minValue {
minValue = array[i]
}
}
return (minValue, maxValue)
}
let tuple = minMaxValue(array: [3,1,2,5,7])
print(tuple)
print(tuple.0) //Access Tuples using a period(.) or dot(.)
print(tuple.1)
//Output
//(minValue: 1, maxValue: 7)
//1
//7
5.Optional Tuple Return Type
Let's see if we see above function "minMaxValue" there is no check for nil value means what is user passed an empty array and in that case it will return nil which will crash our app. So what we have to do is make returned tuple optional using (?) and check for value while printing using 'Optional Binding".
func minMaxValue(array : [Int]) -> (minValue : Int, maxValue : Int)? {
if array.isEmpty {
return nil
}
var maxValue = array[0]
var minValue = array[0]
for i in 1..<array.count {
if array[i] > maxValue {
maxValue = array[i]
}
if array[i] < minValue {
minValue = array[i]
}
}
return (minValue, maxValue)
}
if let valueReturned = minMaxValue(array: [3,1,2]) {
print(valueReturned)
}
//Output if we pass an empty array([])
// Nothing will be printed as function will return nil and optional binding won't allow that print statement to be executed.
//Output if we pass ([3,1,2])
//(minValue: 1, maxValue: 3)
6.Default Parameter Values
We can provide default values for parameters if we are do not always pass that parameter and want a same value if not passed and to overwrite that value if passed.
func addition(a: Int, b: Int = 10) {
print(a + b)
}
addition(a: 10) // 20
addition(a: 10, b: 20) //30
7.In/Out Or Implicit/Explicit parameters
We can use this approach if we want our function's parameters passed to be more readable. We can write multiple names for a parameter passed.
func addition(firstValuePassed numberOne: Int, secondValuePassed numberTwo: Int = 10) {
print(numberOne + numberTwo)
}
addition(firstValuePassed: 10) // 20
addition(firstValuePassed: 10, secondValuePassed: 20) //30
Here in above example i used firstValuePassed as Explicit Parameter name and numberOne as Implicit Parameter name.
What I mean by implicit and explicit value? Implicit means which I am gonna use inside function as parameter name and explicit means which I will be using outside function.
Here I used numberOne inside function and firstValuePassed outside function.
If we do not wish to specify explicit parameter a name and directly pass a value we can omit it with an underscore(_).
func addition(_ numberOne: Int, _ numberTwo: Int = 10) {
print(numberOne + numberTwo)
}
addition(10) // 20
addition(10, 20) //30
Hope, it was helpful and in case any suggestions just comment down.
Top comments (0)