Search code examples
swiftfunctionoopreturn

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?


Solution

  • 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.