swift – 函数和返回值
我是
Swift的初学者,所以有些事情我还不太清楚.我希望有人能向我解释一下:
// 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中制作方法/函数的默认设置. 补充问题! 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.") } } 这是一个简单的代码,但我知道它甚至可能是愚蠢的.我知道应该有一个代码来检查第一个账户中是否有足够的资金从我拿钱,但是好的……让我们玩这个.
所以在Swift中,没有箭头的函数的返回类型为Void:
func funcWithNoReturnType() { //I don't return anything,but I still can return to jump out of the function } 这可以改写为: func funcWithNoReturnType() -> 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,表现为操作成功. 我希望这能清除你所困惑的一点点. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |