Reputation: 173
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?
Upvotes: 6
Views: 12124
Reputation: 2140
Source: https://thenucleargeeks.com/2019/05/08/functions-in-swift/ In swift a function is defined by “func” keyword. When a function is declared based on requirement it may take one or more parameter, process it and return the valueFunction with no parameters and no return value.
Function with no parameter and no return type.
Syntax:
func function_name() {
--
}
func addTwoNumbers() {
let a = 1
let b = 2
let c = a+b
print(c) // 3
}
addTwoNumbers()
Function with no 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
Alternately you can skip the arg and directly pass the value 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 no 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)
Upvotes: 0
Reputation: 1041
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.
Upvotes: 7
Reputation: 4285
This question can be referred as a language-agnostic one, so be my answer to you.
A method is a code block that contains a series of statements. Methods can return a value to the caller, but doesn't have to do so. It is the decision of you as the developer. Method that returns a value to the caller will consist the keyword: "return", and a value type declared in the method signature.
I would mention the Command Query Separation (CQS) principle coined by Bertrand Meyer. Martin Fowler rephrased: The fundamental idea is that we should divide an object's methods into two sharply separated categories:
Upvotes: 0
Reputation: 36653
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.
Upvotes: 3
Reputation: 66244
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, calledsayGoodbye
, which prints its ownString
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.
Upvotes: 1