Press ESC to close

Swift Functions

One of the features we use most in a programming language is its functionality. Before performing the function in Swift, it is rather strange that one used C # and Java before. You get used to it later. If you ask what the function is. It is a block of code written to fulfill a thread.

Our first example is simply to write a function and call it. When creating the function, it must be the “func” at the beginning. Thus, we point out that the code block is a function. Then you can write your code inside the brackets by typing the name of your function and opening and closing parentheses. In this example I print 3 different sentences on the screen. Then I call function with just the name. It’s so simple to create and call functions in Swift.

func fonksiyon()
    print("İlk işlem")
    print("İkinci işlem")
    print("Diğer işlem")


In the second example, the function is how to get the parameter from the outside. We simply write func per function and give the function a name. If we open and close the parentheses, we need to write the parameters that will be taken from the outside. For example, let’s take a name from the outside. Let’s print this name screen. First we write the name of the parameter we get from the outside, and then we put in two dots to tell what type this variable will be. Although it is slightly different from C # and Java, it has its own ease. To use this variable we can call it by writing the name of the variable in parentheses with sweat slash. If we want to use the function again, we write the name of the function and enter the value we will give it.

func DisardanParametre(isim:String)
    print("Hoşgeldiniz \(isim)")
DisardanParametre(isim: "ömer")

Speaking of another example, it will also turn out value. One of the most important features of the functions is to return the value after doing the inside operation. After doing the rituals of our function in the normal way and receiving the parameters from the outside, the value return operations remain. For this, we open the parentheses after closing the function, put the hyphen, put the big-value sign immediately, and specify what type of value we want to return and open the code block with brackets. After doing the operations inside, we call return to return the value and we write the name of the variable. If you look at this part, it looks similar to Java and C #.

func Topla(ilksayi:Int , ikincisayi:Int)->Int
    var toplam = ilksayi - ikincisayi;
    return toplam;

Topla(ilksayi: 23, ikincisayi: 12)

If you have any questions, you can contact me by email or comment.

Leave a Reply

Your email address will not be published. Required fields are marked *