In this post, we will share how to declare a function in Swift programming. This is a very basic program in Swift programming language. If you are Swift beginners or want to start learning Swift programming language, then this program will help you to understand the basic Swift programming.
Copy the below program and create a file named “functionExamples.swift” and execute it.
1 2 3 4 5 6 7 | //Declare a function func sayHelloWorld() { print("Hello World") } //Call function sayHelloWorld() |
1 2 3 4 5 6 7 8 9 10 | // Declare a function with one parameter with a Default value func printName(name : String = "Guest") { print ("Hi \(name)!") } // Call function. // Function will use the parameter value sent printName("Sergey") // Call function. // This time a parameter Default value will be used printName() |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Declare a function that can take variadic parameters func printOutFriendNames(names: String...) { for name in names { print(name) } } // Call the printOutFriendNames with two parameters printOutFriendNames("Sergey", "Bill") // Call the function with more parameters printOutFriendNames("Sergey", "Bill", "Max") |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.