DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on

Day 5 : 100DaysOfSwiftšŸš€

Day 5

Functions

Functions let us re-use code, which means we can write a function to do something interesting then run that function from lots of places.
Repeating code is generally a bad idea, and functions help us avoid doing that.

func printHelp() {
    let message = "Namste Swift"

    print(message)
} 


Enter fullscreen mode Exit fullscreen mode

Run using

printHelp()
//output: Namste Swift

Enter fullscreen mode Exit fullscreen mode

1.Accepting parameter

Values sent into functions this way are called parameters.

func sauChavan(Parameter: DataType){
//code
}

sauChavan(Parameter: argument)


Enter fullscreen mode Exit fullscreen mode

func sauChavan(Surname:String){
    let name="saurabh \(Surname)"
    print(name)
}

sauChavan(Surname:"Chavan")
//Output: saurabh chavan
Enter fullscreen mode Exit fullscreen mode

2.Returning values

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

let result = square(number: 8)
print(result)
Enter fullscreen mode Exit fullscreen mode

3.Parameter labels

func sayHello(to name: String) {
    print("Hello, \(name)!")
}

sayHello(to: "Saurabh")
//output: Hello Saurabh
Enter fullscreen mode Exit fullscreen mode

4.Omitting parameter labels

func Hello(_ person: String) {
    print("Hello, \(person)!")
}
Hello("Saurabh")
//output: Hello Saurabh
Enter fullscreen mode Exit fullscreen mode

You can refer here also best Way and easy Function

Top comments (0)