// 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)
所以这就是代码.我想知道为什么deposit()没有返回箭头和return关键字以及withdraw().我何时使用返回箭头,在什么情况下,是否有规则或其他内容?我不明白.
此外…
每个人都对你的答案如此友善,现在我越来越清楚了.
// Function that return values func myFunction() -> String { return “Hello” }
我想这里不需要这个返回值但是在教程中他们想告诉我们它存在,我是对的吗?
此外,我可以制作一个“错误”,并以某种方式使用我的存款功能中的返回箭头和值吗?我试过这个:
func deposit(amount : Double) -> Double { return balance += amount }
…但它产生了错误.
我在上一家公司看到了高级编码,他们正在创建具有许多自定义和酷炫功能的在线商店,所有代码都充满了返回箭头.这让我很困惑,我认为这是在OOP中制作方法/函数的默认设置.
补充问题!
我想玩函数所以我想创建一个函数transferFunds(),它将钱从一个帐户转移到另一个帐户.我做了这样的功能
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.") } }
这是一个简单的代码,但我知道它甚至可能是愚蠢的.我知道应该有一个代码来检查第一个账户中是否有足够的资金从我拿钱,但是好的……让我们玩这个.
我想在函数transferFunds()中的参数中指定accountNumbers或其他东西,我想搜索我想象中的银行中使用类BankAccount的所有对象/客户端,以便找到一个然后转账.我不知道我是否正确描述了我的问题,但我希望你明白我想做什么.请问有人可以帮助我吗?
func funcWith@R_404_6462@eturnType() { //I don't return anything,but I still can return to jump out of the function }
这可以改写为:
func funcWith@R_404_6462@eturnType() -> Void { //I don't return anything,but I still can return to jump out of the function }
所以在你的情况下……
func deposit(amount : Double) { balance += amount }
您的方法存放采用Type Double的单个参数,并且不返回任何内容,这正是您在方法声明中看不到return语句的原因.这种方法只是在您的帐户中添加或存入更多资金,而不需要退货声明.
但是,在你的撤销方法上:
func withdraw(amount : Double) -> Bool { if balance > amount { balance -= amount return true } else { println("Insufficient funds") return false } }
此方法采用Type Double的单个参数,并返回一个Boolean.关于你的提款方式,如果你的余额低于你试图提取的金额(金额),那么这是不可能的,这就是为什么它返回错误,但如果你的帐户中有足够的钱,它会优雅地撤回资金,并返回true,表现为操作成功.
我希望这能清除你所困惑的一点点.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。