Functions and Return Values

I am new to Swift, so some of the things I don’t quite understand yet. I hope someone explains this to me:

// Creating Type Properties and Type Methods class BankAccount { // stored properties let accountNumber: Int let routingCode = 12345678 var balance: Double class var interestRate: Float { return 2.0 } init(num: Int, initialBalance: Double) { accountNumber = num balance = initialBalance } func deposit(amount: Double) { balance += amount } func withdraw(amount: Double) -> Bool { if balance > amount { balance -= amount return true } else { println("Insufficient funds") return false } } class func example() { // Type methods CANNOT access instance data println("Interest rate is \(interestRate)") } } var firstAccount = BankAccount(num: 11221122, initialBalance: 1000.0) var secondAccount = BankAccount(num: 22113322, initialBalance: 4543.54) BankAccount.interestRate firstAccount.deposit(520) 

So this is the code. I am wondering why deposit() does not have a return arrow and returns a keyword and withdraw() . When I use the return arrow, in what situations is there a rule or something else? I do not understand.

Besides ... Everyone is so kind to your answers, now it becomes clear to me.

At the beginning of this tutorial there is practical code for functions

 // Function that return values func myFunction() -> String { return "Hello" } 

I assume that this return value is not required here, but in the textbook they wanted to show us that it exists, am I right?

Also, can I make a β€œmistake” and use the back arrow and value in my deposit function? I tried with this:

 func deposit(amount : Double) -> Double { return balance += amount } 

... but he generated an error.

I saw advanced coding in my last company, they were creating an online store with a lot of customizable and interesting features, and the whole code was full of return arrows. This confused me, and I thought it was the default for creating methods / functions in OOP.

Additional question! I wanted to play with functions, so I want to create a transferFunds () function that transfers money from one account to another. I made such a function

 func transferFunds(firstAcc : Int, secondAcc : Int, funds : Double) { // magic part if firstAcc == firstAccount.accountNumber { firstAccount.balance -= funds } else { println("Invalid account number! Try again.") } if secondAcc == secondAccount.accountNumber { secondAccount.balance += funds } else { println("Invalid account number! Try again.") } } 

This is a simple code that came to my mind, but I know that it can even be stupid. I know that there should be a code that checks if there are enough funds in the first account, from which I take money, but everything is in order ... I'll play with this. I want to specify accountNumbers or something else in the parameters in the transferFunds() function, and I want to search for all objects / clients in my imaginary bank that use the BankAccount class to find it and then transfer the money. I do not know if I described my problem correctly, but I hope you understand what I want to do. Can someone help me please?

+5
source share
5 answers

So, in Swift, a function that does not have an arrow has a return type of Void :

 func funcWithNoReturnType() { //I don't return anything, but I still can return to jump out of the function } 

This could be rewritten as:

 func funcWithNoReturnType() -> Void { //I don't return anything, but I still can return to jump out of the function } 

so in your case ...

 func deposit(amount : Double) { balance += amount } 

your method deposit accepts one parameter of type Double, and this one returns nothing, so it is you who do not see the return statement in the method declaration. This method simply adds or invests more money to your account where no return statement is required.

However, on your recall method:

 func withdraw(amount : Double) -> Bool { if balance > amount { balance -= amount return true } else { println("Insufficient funds") return false } } 

This method takes a single Type Double parameter and returns a boolean. As for your withdraw method, if your balance is less than the amount you are trying to withdraw (quantity), then this is not possible, therefore it returns false , but if you have enough money in your account, it gracefully withdraws money and returns true to act like this as if the operation was successful.

Hope this makes it a little easier for you to get confused.

+6
source

Welcome to programming! Good questions, stick to it and you will succeed.

Functions that have a return value provide a call code with information. For example, for the deposit function, there is an expectation that nothing unusual will happen, so it will not return anything that can be verified by the caller.

In the withdrawal function, it is possible that the amount to be withdrawn may be greater than the available balance. If so, the function will return false. The calling function can check this value and notify the user that they are trying to remove more than is available. Otoh, if true is returned, the program subtracts this amount from the balance sheet and presumably provides the requested funds to the client.

+3
source

Note Function Parameters and Return Values in Swift Docs:

Functions must not determine the type of return. There is a version of the sayHello function called sayGoodbye that prints its own String value, but does not return it:

 func sayGoodbye(personName: String) { println("Goodbye, \(personName)!") } sayGoodbye("Dave") // prints "Goodbye, Dave!" 

Since it does not need to return a value, the function definition does not include a return arrow (->) or a return type.

In your example, deposit(_:) returns nothing, it just changes the instance variable. This is typical of features that will always succeed.

withdraw(:_) , on the other hand, may fail (due to lack of funds), so it returns a Bool indicating whether it works or not.

+1
source

This question may be called a linguistic agnostic, so be my answer to you.

A method is a block of code containing a series of statements. Methods can return a value to the caller, but this is optional. This is the decision of you as a developer. A method that returns a value to the caller will consist of the keyword: "return" and the type of value declared in the method signature.

I would call the principle of Command Query Separation (CQS), proposed by Bertrand Meyer. Martin Fowler rephrased : The basic idea is that we should divide object methods into two sharply divided categories:

  • Requests Return the result and do not change the observed state of the system (without side effects). Mark Semann said that requests do not mutate the observed state. They are idempotent and call safe.
  • Teams . Change the state of the system, but do not return a value. You can, and safely call requests from commands, but not vice versa.
0
source

Source : https://thenucleargeeks.com/2019/05/08/functions-in-swift/ In swift, a function is defined by the keyword "func". When a function is declared based on a requirement, it can take one or more parameters, process them, and return a valueFunction with no parameters and no return value.

Function without parameter and without return type.

 Syntax: func function_name() { -- } func addTwoNumbers() { let a = 1 let b = 2 let c = a+b print(c) // 3 } addTwoNumbers() 

Function without parameter and return type

 Syntax: func function_name() -> Data Type { -- return some values } func addTwoNumbers()->Int { let a = 1 let b = 2 let c = a+b return c } let sum = addTwoNumbers() print(sum) // 3 

Function with parameter and return type

 Syntax: func function_name(arguments parameter_name: Data Type) -> Data Type { ------ return some values } func addTwoNumbers(arg param: Int)->Int { let a = param let b = 2 let c = a+b return c } let sum = addTwoNumbers(arg: 4) print(sum) // 6 

You can also skip the arg argument and pass the value directly to the function.

 func addTwoNumbers(param: Int)->Int { let a = param let b = 2 let c = a+b return c } let sum = addTwoNumbers(param: 4) print(sum) // 6 

Function with parameter and without return type

 Syntax: func function_name(arguments parameter_name: Data Type) { ---- return some values } func addTwoNumbers(arg param: Int){ let a = param let b = 2 let c = a+b print(c) //6 } addTwoNumbers(arg: 4) 
0
source

All Articles