Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions and returning values

I am a beginner in Swift so some things aren't quite clear to me yet. I hope somebody would explain 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() doesn't have a return arrow and return keyword and withdraw() does. When do I use a return arrow, in what situations, is there a rule or something? I don't understand.

In addition... Everyone is so kind with your answers, it is getting clearer to me now.

In beginning of this tutorial there is practice code for functions

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

I imagine this return value is not needed here but in tutorial they wanted to show us that it exists, am I right?

Furthermore, can I make a "mistake" and use return arrow and value in my deposit function somehow? I tried with this:

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

... but it generated error.

I saw advanced coding in my last firm, they were creating online shop with many custom and cool features and all code was full of return arrows. That confused me and I thought that it is a default for making methods/functions in OOP.

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

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 it is maybe even stupid. I know there should be a code that check if there is enough funds in first account from which I am taking money, but okay... Lets play with this. I want to specify accountNumbers or something else in parameters within function transferFunds() and I want to search through all objects/clients in my imaginary bank which use class BankAccount in order to find one and then transfer money. I don't know if I described my problem correctly but I hope you understand what I want to do. Can somebody help me, please?

like image 976
Antonija Avatar asked Jun 23 '15 16:06

Antonija


3 Answers

So in Swift, a function that has no 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 takes a single parameter of Type Double and this returns nothing, which is exactly why you do not see a return statement in your method declaration. This method is simply adding, or depositing more money into your account, where no return statement is needed.

However, onto your withdraw method:

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

This method takes a single parameter of Type Double, and returns a Boolean. In regard to your withdraw method, if your balance is less than the amount you're trying to withdraw (amount), then that's not possible, which is why it returns false, but if you do have enough money in your account, it gracefully withdraws the money, and returns true, to act as if the operation was successful.

I hope this clears up a little bit of what you were confused on.

like image 58
Justin Rose Avatar answered Sep 17 '22 14:09

Justin Rose


Welcome to programming! Good questions, stick with it and you'll do well.

The functions that have a return value are providing the calling code with information. For example, for the deposit function, there is the expectation that nothing unusual will happen, so it's not bothering to return anything that could be checked by the caller.

In the withdrawal function, it's possible that the amount to be withdrawn could be greater than the balance available. If this is the case, the function will return false. The calling function could check that value and notify the user that they're attempting to withdraw more than is available. Otoh, if a value of true is returned, then the program will deduct that amount from the balance and presumably provide the customer with the funds requested.

like image 34
Jack BeNimble Avatar answered Sep 20 '22 14:09

Jack BeNimble


Check out Function Parameters and Return Values in the Swift docs:

Functions are not required to define a return type. Here’s a version of the sayHello function, called sayGoodbye, which prints its own String value rather than returning it:

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

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

In your example, deposit(_:) doesn't return anything, it just modifies an instance variable. This is typical of functions which will always succeed.

withdraw(:_), on the other hand, might fail (due to insufficient funds), so it returns a Bool indicating whether it worked or not.

like image 25
Aaron Brager Avatar answered Sep 18 '22 14:09

Aaron Brager